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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | $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 |
Disclaimer: All posts and opinions on this site are provided AS IS with no warranties. These are our own personal opinions and do not represent our employer’s view in any way.
This article currently have 4,976 views
Latest posts by Saugata (see all)
This work is licensed under a Creative Commons Attribution-NoDerivatives 4.0 International License.