AD Groups Script Examples (PowerShell)

From vwiki
Revision as of 09:48, 21 June 2013 by Sstrutt (talk | contribs) (Initial creation)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Group Member Deduplication

This script is for use when you want to remove users/members from one group that also exist in another. It gets a list of users from both groups and then compares, removing duplicates from one of the groups.

$RefGroupName = "Group A"                                # Reference group (which isn't touched)
$ModGroupName = "Group B"                                # Group to have users removed from if they exist in the above group

$MakeChanges = $true                                     # Set to $false to see what would be done

$cred = Get-Credential -Message "Domain Admin user/pass"

Import-Module ActiveDirectory

$RefGroup = Get-ADGroup $RefGroupName
$RefGroupMembers = Get-ADGroupMember $RefGroup

$ModGroup = Get-ADGroup $ModGroupName
$ModGroupMembers = Get-ADGroupMember $ModGroupName

foreach ($user in $ModGroupMembers) {
    if ($user.objectClass -ne "user") {
        Write-Host ("Skipping non-user " + $user.Name)
        Continue
    }

    if ($RefGroupMembers | ?{$_.SamAccountName -eq $user.SamAccountName}) {
        Write-Host ($user.SamAccountName + " (" + $user.Name + ") exists in both groups")
        if ($MakeChanges) {
            Remove-ADGroupMember -Identity $ModGroup -Members $user -Confirm:$false -Credential $cred
            Write-Host ($user.SamAccountName + " (" + $user.Name + ") removed from $ModGroupName")
        }
         
    } else {
        Write-Host ($user.SamAccountName + " (" + $user.Name + ") exists in only $ModGroupName")
    }
}