Cleanup Active Directory groups with PowerShell

The estimated reading time 2 minutes

Taking care for local Active Directory (if it is still present) is one of the most important tasks, so you may need also cleanup disabled users from groups. Sometimes you don’t want to delete users but only removing them from AD groups is required (often for licensing issues etc.)

I’ve had that case and wrote a small PowerShell script therefore. This script searches for the disabled members of an AD group and can also remove them. This can also be executed against distribution groups for Microsoft Exchange.
NOTE: if there are Shared Mailboxes /Room Mailboxes as members, they will be remove also, because the AD user is also disabled.

Let’s have a look at the script finally. If you copy the whole script it does not remove anyone from the group, because it’s in “simulation” mode. To execute the removal you need to remove the “-whatif” in line 23.

#type the adgroup name to check
$grouptoclean = "XXXXX"

####
$dcfqdn  = ((Get-ADDomainController).Hostname)

$groupmembers = Get-ADGroupMember -Server $dcfqdn -Identity $grouptoclean  | sort

$inactiveusers = @()
foreach($user in $groupmembers){

  $dist = ($user).distinguishedName
  
  $enabled = Get-ADUser -Server $dcfqdn -Identity "$dist" | Where-Object{$_.enabled -eq $false}
  $sam = ($enabled).SamAccountName
  $upn = ($enabled).UserPrincipalName
  $active = ($enabled).Enabled
  
  if($enabled){
    Write-Host "UPN: $upn , SAM: $sam is disabeld, Status: $active" -ForegroundColor Yellow
    $inactiveusers += $sam 
    Remove-ADGroupMember -Identity $grouptoclean -Members $sam -server $dcfqdn -Confirm:$false -WhatIf
    
  }
  else{
      $member = Get-ADUser -Server $dcfqdn -Identity "$dist"
      
      $sammember = ($member).SamAccountName
      $upnmember = ($member).UserPrincipalName
      $activemember = ($member).Enabled
      
    Write-Host "UPN: $upnmember, SamAccountName: $sammember Status: $activemember"
  
  } 
  
 
} 


$inactiveusers

($inactiveusers).count 

#$inactiveusers = $null

The PowerShell console displays all disabled users which it would also remove.

Using the variable “$inactiveusers” you can retrieve all inactive members of the group you’ve chosen. After executing the script the second time with the same console session users will be added, be careful. To clear up this variable you can use the last line “$inactiveusers = $null”.

With “($inactiveusers).count” it is very easy to count all inactive members.

Have fun cleaning up your local AD groups. If you liked this article please klick on helpful.

Print Friendly, PDF & Email
Was this article helpful?
YesNo
5 1 vote
Article Rating
Subscribe
Notify of
guest
4 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Yann Quéré
Yann Quéré
13 hours ago

what about cleaning the SID for deleted users coming from others forest ?

Dinesh
Dinesh
5 months ago

What if the group has nested groups?