远程Windows服务器上创建本地用户,并添加到管理员组
问题描述:
我创建PowerShell脚本来创建用户远程Windows服务器上,并添加到管理员组:远程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
答
:我有固定的代码。您正在使用只返回,如果它已经存在的用户帐户声明:
$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"
答
我想你错过了“管理员”下面的“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)
尼斯风风火火得到正确AdminGroup的名字! –
@Ansgar Wiechers - 非常感谢用户添加了Remote作品,但是尽管设置了上述设置,但它并未添加到Administrators组中。 –