PowerShell: Adding a User to Local Groups

Adding User(s) to Local Groups
# addUserToLocalGroup.ps1
# Version 0.02

$computernames=@(
    'SERVER0001',
    'SERVER0002'
    )
$accountsToAdd='domain\user1','domain\user2'
$accountPassword=$null # set this value to Null in cases of existing accounts
$localgroup='Remote Desktop Users'
$adminCredentials=$null

function addUserToLocalGroup{
    param(
    $computernames=$env:computername,
    $accountsToAdd,
    $accountPassword=$null,
    $localGroup='Administrators',
    $adminCredentials=$null
    )
    foreach ($computername in $computernames){
        try{
            $session=if($adminCredentials){
                new-pssession $computername -Credential $adminCredentials -ea Stop
              }else{
                new-pssession $computername -ea Stop
              }        
        }catch{
            write-warning $_
            return $false
            }
        invoke-command -session $session -scriptblock{
            param($principleNames,$password,$groupName)
            $results=@()
            $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 -ea stop).Name
            }catch{
                $x=net localgroup $groupName
                $x[6..$($x.length-3)]
            }
            $localUsers=try{
                (get-localuser).Name
            }catch{
                $x=net user # Legacy backward compatible
                $x[4..$($x.length-3)] -split ' '|?{$_.trim()}
            }
            # write-host "Attempting to add $($principleNames -join ',') into '$groupName' on $env:computername"
            foreach($principle in $principleNames){
                if(!($members|?{$_ -eq $principle})){
                    try{
                        if(!($localUsers|?{$_ -eq $principle}) -and ($principle|?{$_ -notmatch '\\'})){
                            if($osVersion -gt [version]'6.3.9600.0' -or $psVersion -ge [version]'5.1'){
                                $encryptedPass = ConvertTo-SecureString $password -AsPlainText -Force
                                New-LocalUser -name $principle -Password $encryptedPass -FullName "$principle"
                            }else{
                                $null=net user $principle "$password" /add /passwordreq:yes /fullname:"$principle"
                            }            
                        }                        
                        if($osVersion -gt [version]'6.3.9600.0' -or $psVersion -ge [version]'5.1'){
                            Add-LocalGroupMember -Group $groupName -Member $principle -ea Stop
                        }else{
                            $null=net localgroup $groupName /add $principle
                        }             
                    }catch{
                        write-warning "$error"
                    }
                }else{
                    write-host "$principle is already a member of group '$groupName'"
                }
            }
            $currentMembers=try{
                (get-localgroupmember $groupName -ea stop).Name
            }catch{
                $x=net localgroup $groupName
                $x[6..$($x.length-3)]
            }
            write-host "Commands completed.`r`n`r`nCurrent members of $groupName`:`r`n$($currentMembers|out-string)"
            foreach($principle in $principleNames){
                $results+=[pscustomobject]@{
                    computername=$env:computername
                    groupname=$groupName
                    userName=$principle
                    usernameIsMember=[bool]($principle -in $currentMembers)
                }
            }
            return $results
        } -ArgumentList $accountsToAdd,$accountPassword,$localGroup|select-object * -ExcludeProperty PSComputerName,RunspaceId
        remove-pssession $session        
    }
}

$results=addUserToLocalGroup $computernames $accountsToAdd $newPassword $localGroup $adminCredentials
# Sample Output
intranet\kimconnect is already a member of group Remote Desktop Users
intranet\mulan is already a member of group Remote Desktop Users
Commands completed.

Current members of Remote Desktop Users:
intranet\Domain Admins
intranet\kimconnect
intranet\mulan

PS C:\Windows\system32> $results
computername     : SERVER0001
groupname        : Remote Desktop Users
userName         : intranet\kimconnect
usernameIsMember : True

computername     : SERVER0001
groupname        : Remote Desktop Users
userName         : intranet\mulan
usernameIsMember : True
# Version 0.01 (deprecated)
$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 *