Slightly new to powershell and looking for some guidance. I'm trying to create a simple script to accomplish the following:
- Check if a local ID already exists on a list of servers
- If not, create one and add to local administrator group across the list of servers
- Log out results
$serverlist = Get-Content C:\temp\servers.txt
$credential = Get-Credential
foreach ($server in $serverlist){
#User to search for
$USERNAME = "John"
#Declare LocalUser Object
$ObjLocalUser = $null
Invoke-Command -Credential $credential -Authentication Default -ComputerName $Server -ScriptBlock {
$ObjLocalUser = Get-LocalUser "John"
#Create the user if it was not found (Example)
if (!$ObjLocalUser) {
Write-Verbose "Creating User $($USERNAME)" #(Example)
NET USER "John" "Generic Password" /ADD /passwordchg:no
NET LOCALGROUP "Administrators" "Joe Doe" /ADD
}
else {
Write-Verbose "John" already exists"
}
}
}
P.S, just using generic credentials for simplicity, will convert to best standards afterwards. Just trying to get more experience writing some Powershell and would probably convert to a custom function later on.
According to your script, I note the following points that could be enhanced
1- you don't have to use the for loop to iterate through the servers list, instead you can pass the server list array directly to the
ComputerNameparameter of theInvoke-Commandso in your script you could use it as follow
2- in the
Invoke-Command, you search if the user exist or not using the commandbut this will give you an error if the user doesn't exist
instead of that you could search for the user using:
3- you don't need to use the variable
$ObjLocalUser, you could check directly the search result using the if condition as follow:Finally: in order to use the a local variable inside the
invoke-commndyou could use theUsingscope modifier to identify a local variable in a remote command.so the script could be something like that: