Hi, I am not a PowerShell expert by any means. Using google I was able to construct a script but it’s not quite working as intended. It’s supposed to create a local admin account on a list of servers from a text file. As it is creating the file it’s supposed to check if the server is online and if so, check to see if the account already exists.
Well, the creation part works but the correct error message is not returned when the account does exist. Can someone please help?
Thanks.
$UserName = "ADMIN2"
$Password = Read-Host "What password would you like to use?" -AsSecureString
$Message1 = "Account already exists"
$Message2 = "Server Unreachable"
$Message3 = "ADMIN2 Created"
Loop through the list of servers
Get-Content c:\AI\Serversmini2.txt | ForEach-Object {
$ServerName = $_
$User = $null
$exaccount=$null
# Connect to the server. Connection is used to create users.
$Server = [ADSI]“WinNT://$ServerName”
# Check for connectivity to server
if (test-connection $ServerName -Count 1) {
# Connect to the administrators group so we can add members.
$AdminGroup = [ADSI]"WinNT://$ServerName/Administrators, group"
$exaccount = (get-ciminstance win32_useraccount -filter "localaccount='true' and name='ADMIN2'")
if ($exaccount -eq $null) {
# Create the user
$User = $Server.Create('User', $UserName)
# Set password
$User.SetPassword("$Password")
# Set Password to never expire
$flag = $User.UserFlags = 65536
# Save the changes
$User.SetInfo()
# Add the new user to the admin group
$AdminGroup.Add($User.Path)
$Server, $Message3 | Out-File -Append C:\AI\AccountCreation.txt
}
Else{
$Server, $Message1 | Out-File -Append C:\AI\AccountCreation.txt
}
}
Else{
$Server, $Message2 | Out-File -Append C:\AI\AccountCreation.txt
}
}