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.
$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
The Credential-Free Watchdog: Mastering Event-Driven App Automation
We have all been there. You are an automation lover. You have…
Multi-Thread Super-Fast Software Inventory Scan using WSMan (PowerShell Remoting)
Recently I was asked to pull the software inventory report from multiple…
Setup your own Monitoring – Disk Space Utilization Monitoring tool for free
It is always recommended to keep tracking of the disk space utilization…
Port Scanner using PowerShell with Email Notification
Few days back I was asked to create a script, which will…