PowerShell: Adding a User to Local Groups

Adding User(s) to Local Groups
$remoteComputers='SERVER1','SERVER1000'
$newMembers='testUser'
$newPassword='PASSWORD'
$localGroup='Remote Desktop Users'
$domainAdminCred=$null

function addUserToLocalGroup{
    param(
    $computername=$env:computername,
    $accountToAdd,
    $accountPassword=$null,
    $localGroup='Administrators',
    $domainAdminCred=$null
    )
    try{
        $session=if($domainAdminCred){
            new-pssession $computername -Credential $domainAdminCred -ea Stop
          }else{
            new-pssession $computername -ea Stop
          }        
    }catch{
        write-warning $_
        return $false
        }
    invoke-command -session $session -scriptblock{
        param($principleName,$password,$groupName)
        $osVersion=[System.Environment]::OSVersion.Version
        $psVersion=$PSVersionTable.PSVersion
        $computerRole=switch ((Get-WmiObject Win32_OperatingSystem -EA Silentlycontinue).ProductType){
            1 {'client'} # ClientOs
            2 {'domaincontroller'} #ServerOs with DC role
            3 {'memberserver'} #ServerOs machines
            }
        if($computerRole -eq 'domaincontroller'){
            write-warning "$env:computername is a Domain Controller. Local Users and Groups are not applicable."
            return $false
        }
        $members=try{
            (get-localgroupmember $groupName).Name
        }catch{
            $x=net localgroup $groupName
            $x[6..$($x.length-3)]
        }
        $localUsers=try{
            (get-localuser).Name
        }catch{
            $x=net user
            $x[4..$($x.length-3)] -split ' '|?{$_.trim()}
        }

        if(!($members|?{$_ -eq $principleName -or $_ -eq "$env:computername\$principleName"})){ # backward compatible with legacy PowerShell
            try{
                if(!($localUsers|?{$_ -eq $principleName}) -and $principleName -notmatch '\\'){
                    if($osVersion -gt [version]'6.3.9600.0' -or $psVersion -ge [version]'5.1'){
                        $encryptedPass = ConvertTo-SecureString $password -AsPlainText -Force
                        New-LocalUser -name $principleName -Password $encryptedPass -FullName "$principleName"
                    }else{
                        $null=net user $principleName "$password" /add /passwordreq:yes /fullname:"$principleName"
                    }            
                }
                write-host "Adding $principleName into $groupName on $env:computername"                
                if($osVersion -gt [version]'6.3.9600.0' -or $psVersion -ge [version]'5.1'){
                    Add-LocalGroupMember -Group $groupName -Member $principleName -ea Stop
                }else{
                    $null=net localgroup $groupName /add $principleName
                }
                $currentMembers=try{
                    (get-localgroupmember $groupName).Name
                }catch{
                    $x=net localgroup $groupName
                    $x[6..$($x.length-3)]
                }
                if($currentMembers|?{$principleName -eq $_}){
                    write-host "$principleName has been added to $groupName successfully`r`n$($currentMembers|out-string)"
                    return $true
                }else{
                    write-host "$principleName has NOT been added into group $groupName`r`n$($currentMembers|out-string)"
                    return $false
                }               
            }catch{
                write-warning "$error"
                return $false
                }
        }else{
            write-host "$principleName is already a member of $groupName."
            return $true}
        } -args $accountToAdd,$accountPassword,$localGroup
    remove-pssession $session
}

$remoteComputers|%{
    $computer=$_;
    write-host "Checking $computer..."
    $newMembers|%{addUserToLocalGroup $computer $_ $newPassword $localGroup $domainAdminCred}
}
Removing User(s) from Local Groups
function removeUserFromLocalGroup{
    param(
    $computername=$env:computername,
    $accountToAdd,
    $localGroup='Administrators',
    $domainAdminCred=$null
    )
    try{
        $session=if($domainAdminCred){
            new-pssession $computername -Credential $domainAdminCred -ea Stop
          }else{
            new-pssession $computername -ea Stop
          }        
        }
    catch{
        write-warning $_
        return $false
        }
    invoke-command -session $session -scriptblock{
        param($principleName,$groupName)
        $osVersion=[System.Environment]::OSVersion.Version
        $psVersion=$PSVersionTable.PSVersion
        $members=try{
            (get-localgroupmember $groupName).Name
        }catch{
            $x=net localgroup $groupName
            $x[6..$($x.length-3)]
        }
        $matchMember=if($principleName -in $members){
                $principleName
            }elseif("$env:computername\$principleName" -in $members){
                "$env:computername\$principleName"
            }else{
                $null
            }
        if($matchMember){
            try{
                write-host "Removing $matchMember from $groupName on $env:computername"                
                if($osVersion -gt [version]'6.3.9600.0' -or $psVersion -ge [version]'5.1'){
                    Remove-LocalGroupMember -Group $groupName -Member $matchMember -ea Stop
                }else{
                    $null=net localgroup $groupName /del $matchMember
                }
                $currentMembers=try{
                    (get-localgroupmember $groupName).Name
                }catch{
                    $x=net localgroup $groupName
                    $x[6..$($x.length-3)]
                }
                if($matchMember -notin $currentMembers){
                    write-host "$matchMember has been deleted from $groupName successfully`r`n"
                    write-host "Result:`r`n$($currentMembers|out-string)"
                    return $true
                }else{
                    write-host "$matchMember still exists in group $groupName`r`n"
                    write-host "Result:`r`n$($currentMembers|out-string)"
                    return $false
                }               
            }catch{
                write-warning "$error"
                return $false
                }
        }else{
            write-host "$principleName is current NOT a member of $groupName."
            return $true
        }
        } -args $accountToAdd,$localGroup
    remove-pssession $session
}

removeUserFromLocalGroup $env:computername 'Domain\UserName' 'Remote Desktop Users'

Leave a Reply

Your email address will not be published. Required fields are marked *