Demonstrates how to add a user to a local Windows group.
$username = 'SomeUserName'
$localGroup = 'Administrators'
$members = net localgroup $localGroup
$result = $members | Select-String $username
if ($result.Count -eq 0) {
Write-Host "Adding $username to $localGroup"
net localgroup $localGroup $username /add
}
else {
Write-Host "$username is already a member of $localGroup"
}
# ---------
Write-Host 'Adding accounts to local Administrator group on servers...' -ForegroundColor Cyan
Invoke-Command -ComputerName 'server_one', 'server_two' -ScriptBlock {
$usernames = @('user_one', 'user_two', 'user_three')
$localGroup = 'Administrators'
foreach ($username in $usernames)
{
$members = net localgroup $localGroup
$result = $members | Select-String $username
if ($result.Count -eq 0)
{
Write-Host "Adding $username to $localGroup on $Env:COMPUTERNAME"
net localgroup $localGroup $username /add
}
else
{
Write-Host "$username is already a member of $localGroup on $Env:COMPUTERNAME"
}
}
}