2017-04-07 47 views
1

我創建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 

回答

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" 
+0

尼斯風風火火得到正確AdminGroup的名字! –

+0

@Ansgar Wiechers - 非常感謝用戶添加了Remote作品,但是儘管設置了上述設置,但它並未添加到Administrators組中。 –

0

我想你錯過了「管理員」下面的「s」。

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

我有(工作)腳本,將用戶添加到本地管理員組和該行看起來是這樣的:

$AdminGroup = [ADSI]"WinNT://$ComputerName/Administrators,group" 
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) 
相關問題