在远程Windows Server上创建本地用户并添加到管理员组

时间:2017-04-07 11:20:25

标签: powershell wmi powershell-remoting get-wmiobject

我已创建PowerShell脚本以在远程Windows Server上创建用户并添加到管理员组:

$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)

它给了我以下错误:

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

3 个答案:

答案 0 :(得分:3)

如果要创建用户,则需要实际创建用户。您正在使用的语句仅在用户帐户已存在时才会返回该用户帐户:

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

创建本地帐户的最简单方法可能是net命令:

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

使用WinNT provider是可能的,但更复杂:

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

另外,正如其他人已经指出的那样,你拼错了管理员组的名称(这就是造成第二个错误的原因)。由于该组的名称可以本地化,具体取决于您正在运行的语言版本,您可能还是想要解决它:

$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"

答案 1 :(得分:0)

我认为你错过了一个&#34; s&#34;在&#34;管理员&#34;下方。

$AdminGroup = [ADSI]"WinNT://$Computer/Administrator,group"

我有一个(工作)脚本,将用户添加到本地管理员组,该行如下所示:

$AdminGroup = [ADSI]"WinNT://$ComputerName/Administrators,group"

答案 2 :(得分:0)

你实际上从未创建过用户。您还想要更正管理员组名称。我修改了你的代码:

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