我正在尝试通过 powershell 在远程计算机上创建用户。创建帐户后,我想将其添加到本地管理员组中。
帐户正在创建,但尚未添加到管理员组中。以下是我正在使用的代码。
cls
$username = "test_user"
$password = "password"
$computer1 = hostname
$users = $null
$computer = [ADSI]“WinNT://$computer1”
Try {
$users = $computer.psbase.children | select -expand name
if ($users -like $username) {
Write-Host "$username already exists"
} Else {
$user_obj = $computer.Create(“user”, “$username”)
$user_obj.SetPassword($password)
$user_obj.SetInfo()
$user_obj.Put(“description”, “$username”)
$user_obj.SetInfo()
$user_obj.psbase.invokeset(“AccountDisabled”, “False”)
$user_obj.SetInfo()
$users = $computer.psbase.children | select -expand name
if ($users -like $username) {
Write-Host "$username has been created on $($computer.name)"
$group = [ADSI]("WinNT://"+$env:COMPUTERNAME+"/administrators,group")
$group.add("WinNT://$env:localhost/$username,user")
} Else {
Write-Host "$username has not been created on $($computer.name)"
}
}
} Catch {
Write-Host "Error creating $username on $($computer.path): $($Error[0].Exception.Message)"
}
请告知我做错了什么。
答案1
实际上复制粘贴的脚本根本不起作用。
它有无效的双引号:“
和”
它通过三种不同的方式引用本地计算机:
[ADSI]“WinNT://$computer1”
[ADSI]("WinNT://"+$env:COMPUTERNAME+"
WinNT://$env:localhost/
有几种情况,文本没有被正确引用并与变量分隔/连接。
这有效:
cls
$username = "test_user"
$password = "zlug7nPn5$"
$computername = "ComputerName"
$users = $null
$computer = [ADSI]"WinNT://$computername"
Try {
$users = $computer.psbase.children | select -expand name
if ($users -like $username) {
Write-Host "$username already exists"
} Else {
$user_obj = $computer.Create("user", "$username")
$user_obj.SetPassword($password)
$user_obj.SetInfo()
$user_obj.Put("description", "$username")
$user_obj.SetInfo()
$user_obj.psbase.invokeset("AccountDisabled", "False")
$user_obj.SetInfo()
$users = $computer.psbase.children | select -expand name
if ($users -like $username) {
Write-Host "$username has been created on $($computer.name)"
$group = [ADSI]("WinNT://"+$computername+"/administrators,group")
$group.add("WinNT://"+$computername+"/"+$username+",user")
} Else {
Write-Host "$username has not been created on $($computer.name)"
}
}
} Catch {
Write-Host "Error creating $username on $($computer.path): $($Error[0].Exception.Message)"
}
答案2
使用 Add-localgroupmember 命令怎么样? https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/add-localgroupmember
与用户创建相同,New-Localuser。