我的服务器数量很少,其中“tempadmin”和“Administrator”作为本地管理员用户存在。如果“Administrator”也存在,我需要删除“tempadmin”id。否则“tempadmin”需要重命名为“Administrator”。任何人都可以帮我创建一个PowerShell脚本吗?
cls
$strComputer = Get-Content "c:\patch\clientlist.txt"
$password = Read-Host "Enter the password : " -AsSecureString
foreach ($server in $strComputer) {
Write-Host "Working on server $server"
if (Test-Connection $server -Quiet) {
$usertest1 = Get-WMIObject Win32_UserAccount -Filter "LocalAccount=True AND Name='test1'" -ComputerName $server
if ($usertest1.name -ne 'test1') {
$user = Get-WMIObject Win32_UserAccount -Filter "LocalAccount=True AND Name='test'" -ComputerName $server
$result = $user.Rename('test1')
if ($result.name -eq 'test') {
$result
# you may just print a message here
}
Write-host "$server -> ID renamed and resetting password...."
$user1 = Get-WMIObject Win32_UserAccount -Filter "LocalAccount=True AND Name='test1'" -ComputerName $server
([adsi]("WinNT://" + $server + "$user1")).SetPassword("$password")
Write-Host "$server -> Password reset successfully"
} else {
Write-Host "$server -> Test1 ID already exist"
}
} else {
Write-Host "$server -> server is not reachable"
}
}
这里我是用户“test”和“test1”。我尝试了上面的代码,我可以成功重命名并重置密码。但如果两个ID都存在,我无法删除。
答案 0 :(得分:0)
我会尝试这样的事情:
$VerbosePreference = 'Continue'
foreach ($C in $Computer) {
if (Test-Connection $C -Quiet) {
Write-Verbose "$C > Online"
$Users = Get-WMIObject Win32_UserAccount -Filter "LocalAccount=True" -ComputerName $C
if ($Users.Name -contains 'Administrator') {
Write-Verbose "User 'Administrator' found"
if ($Users.Name -contains 'tempadmin') {
Write-Verbose "Delete user 'tempadmin'"
$ADSI = [ADSI]"WinNT://$C"
$ADSI.Delete('User','tempadmin')
}
}
else {
Write-Verbose "User 'Administrator' not found"
# Here you can rename the 'tempadmin' account or create a new 'Administrator'
}
}
else {
Write-Verbose "$C > Offline"
}
}
这还不完整,但我相信你会在这里得到这个想法。最好先查询一次客户端然后遍历对象集合,而不是多次查询以检查每个查询中的不同对象。
我希望这可以帮助你或给你一些想法。
可在Boe Pox's excellent blog找到更多信息。