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

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

我已经创建了 PowerShell 脚本来在远程 Windows 服务器上创建用户并添加到管理员组:

$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

我认为您在下面的 "administrators" 中遗漏了一个 "s"。

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

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

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

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

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

如果您想创建一个用户,您需要实际创建一个用户。您正在使用的声明 returns 仅当用户帐户已经存在时:

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