Hello,
I am creating a PowerShell script that creates a local account and adds it to de local administrators group.
The creating of the account is succesvol, but the adding to the local group fails.
My code is as follows:
$rComputer = [ADSI]"WinNT://$sComputer,computer"
#$sLocalAdminUser = "Account"
# creating of the user account
# user account succesvol added
if($bAddUser -eq $True)
{
# checking if user really exsists
if([ADSI]::Exists("WinNT://$sComputer/$sLocalAdminUser,user")) {
write-host "User exists, adding to local admin group"
try {
$rGroup = $rComputer.psbase.children.find("Administrators")
$rGroup.Add(([ADSI]"WinNT://$sComputer/$sLocalAdminUser,user").path)
$bAddGroup = $True
} catch {
write-host $_.Exception.Message
$bAddGroup = $False
}
} else {
write-host "User does not exist"
}
}
The weird thing is, the user exists and the [ADSI]::Exists check verifies that the user exists.
But when I try to add the user to the localgroup it results in an error:
Exception calling “Add” with “1” argument(s): “A member could not be added to or removed from the local group because the member does not exist.”
When I first run the code for adding a new user and then manually use Powershell to add the user to the group it does work.
Can somebody tell me what’s wrong?