Search code examples
powershellwmipowershell-remotingget-wmiobject

Creating Local User on Remote Windows Server and Add to Administrator Group


I have Created PowerShell script to create User on remote Windows Server and add to Administrator group:

$Computer = Read-Host "Computer name:"
$UserName = Read-Host "User name:"
$Password = Read-Host "Password" -AsSecureString
$AdminGroup = [ADSI]"WinNT://$Computer/Administrator,group"
$User = [ADSI]"WinNT://$Computer/$UserName,user"
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserName, (ConvertTo-SecureString $Password -AsPlainText –Force)
$User.SetPassword($Cred.GetNetworkCredential().Password)
$AdminGroup.Add($User.Path)

And It gives me below error:

The following exception occurred while retrieving member "SetPassword":                "
The user name could not be found.
At C:\test1.ps1:7 char:18
+ $User.SetPassword <<<< ($Cred.GetNetworkCredential().Password)
    + CategoryInfo          : NotSpecified: (:) [],  ExtendedTypeSystemException
    + FullyQualifiedErrorId : CatchFromBaseGetMember

The following exception occurred while retrieving member "Add": "The specified
local group does not exist.
At C:\test1.ps1:8 char:16
+ $AdminGroup.Add <<<< ($User.Path)
    + CategoryInfo          : NotSpecified: (:) [],  ExtendedTypeSystemException
    + FullyQualifiedErrorId : CatchFromBaseGetMember

Solution

  • If you want to create a user you need to actually create a user. The statement you're using returns a user account only if it already exists:

    $User = [ADSI]"WinNT://$Computer/$UserName,user"
    

    Probably the simplest way to create a local account is the net command:

    & net user $UserName ($Cred.GetNetworkCredential().Password) /expires:never /add
    

    Using the WinNT provider is possible, but more complicated:

    $acct = [adsi]"WinNT://$Computer"
    $user = $acct.Create('User', $UserName)
    $user.SetPassword($Cred.GetNetworkCredential().Password)
    $user.SetInfo()
    

    Also, as others have already pointed out, you misspelled the name of the administrators group (that's what's causing the second error). Since the name of that group could be localized, depending on what language version you're running, you may want to resolve it anyway:

    $AdminGroupName = Get-WmiObject Win32_Group -Filter "LocalAccount=True AND SID='S-1-5-32-544'" |
                      Select-Object -Expand Name
    $AdminGroup = [adsi]"WinNT://$Computer/$AdminGroupName,group"