Cleanup disabled users from AD Group/s

Cleanup disabled accounts from groups is one of the most boring job, and also take lots of time. Manually it’s almost impossible to maintain. Recently I had a request to perform such task for many groups, so, I wrote a script to do it automatically on behalf of me. I am now sharing this script, hoping this might help you as well.

This script will do following task automatically.

  • Get the members of a group.
  • Identify only users.
  • Identify disabled users.
  • Check every disabled users group memberships.
  • Remove the disabled users from that group.
  • Generate a report with status (success / failure).
  • Keep the report on your desktop.
powershellCleanup disabled users from AD Group
$GroupSamName = "You-AD-Group-Name"
$ErrorReport=@()
foreach ($member in (Get-ADObject -Filter {(SamAccountName -eq $GroupSamName)} -Properties *).Member)
{
    $GetADUser=$null
    $DServer = $null
    $DServer=$(($member.Split(",") | Select-String DC= | % {$_.ToString()}).Replace("DC=","") -join ".")
    if ($(Get-ADObject -Filter {(DistinguishedName -eq $member)} -Server $DServer | ? {$_.ObjectClass -ne "group" -AND $_.ObjectClass -ne "computer"}).DistinguishedName){$GetADUser = Get-ADUser $member -Properties Enabled -Server $DServer}
    #$GetADUser
    if (($GetADUser).Enabled -eq $false) {
        $GetUserGroups = (Get-ADObject -Filter {(DistinguishedName -eq $member)} -Properties Memberof).Memberof
        foreach($Group in $GetUserGroups)
        {
            try{
                #"$($Group.Split(",")[0].Split("=")[1])"
                Remove-ADGroupMember -Identity $Group -Members $GetADUser -Server $(($Group.Split(",") | Select-String DC= |% {$_.ToString()}).Replace("DC=","") -join ".") -Confirm:$false
                $MyObject = New-Object PSObject -Property @{ 
                UserName="$member"            
                GroupName="$($Group.Split(",")[0].Split("=")[1])"
                RemovalStatus = "Removed"
                }
                $ErrorReport += $MyObject
            $MyObject
            }catch{
                $MyObject = New-Object PSObject -Property @{ 
                UserName="$member"            
                GroupName="$($Group.Split(",")[0].Split("=")[1])"
                RemovalStatus = "$($_.Exception.ToString().Split("-")[0].Split(":")[1].Trim())"
                }
                $ErrorReport += $MyObject
            $MyObject
            }
        }
    }
}
$ErrorReport | Export-Csv -NoTypeInformation $env:USERPROFILE\Desktop\Report.csv

Leave a Reply

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