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

久未见 提交于 2019-12-08 03:20:29

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"

You actually never created user. Also you want to correct Administrators group name. I have fixed your code:

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

I think you're missing an "s" in "administrators" below.

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

I have a (working) script that adds a user to the local administrators group and that line looks like this:

$AdminGroup = [ADSI]"WinNT://$ComputerName/Administrators,group"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!