i am trying to create user on remote machine by powershell. Once account created i want to add that in local admin group.
Account is getting created but it is not getting added in admin group.
Below is the code which i am using.
cls
$username = "test_user"
$password = "password"
$computer1 = hostname
$users = $null
$computer = [ADSI]“WinNT://$computer1”
Try {
$users = $computer.psbase.children | select -expand name
if ($users -like $username) {
Write-Host "$username already exists"
} Else {
$user_obj = $computer.Create(“user”, “$username”)
$user_obj.SetPassword($password)
$user_obj.SetInfo()
$user_obj.Put(“description”, “$username”)
$user_obj.SetInfo()
$user_obj.psbase.invokeset(“AccountDisabled”, “False”)
$user_obj.SetInfo()
$users = $computer.psbase.children | select -expand name
if ($users -like $username) {
Write-Host "$username has been created on $($computer.name)"
$group = [ADSI]("WinNT://"+$env:COMPUTERNAME+"/administrators,group")
$group.add("WinNT://$env:localhost/$username,user")
} Else {
Write-Host "$username has not been created on $($computer.name)"
}
}
} Catch {
Write-Host "Error creating $username on $($computer.path): $($Error[0].Exception.Message)"
}
Please advise what am i doing wrong.
Best Answer
Actually the script that was copied and pasted does not work at all.
It has invalid double quotes:
“
and”
It references the local computer in three different ways:
[ADSI]“WinNT://$computer1”
[ADSI]("WinNT://"+$env:COMPUTERNAME+"
WinNT://$env:localhost/
There are several occurrences where text is not quoted properly and separated/concatenated with variables.
This works: