Finding Groups that have disabled users in them

This is just a quick powershell script to find all users who are a member of a certain group (of certain groups).
We were running out of licenses for one of the products we use internally. This product is tied to group memberships. Instead of clicking on each indivual group or disabled user (approximate 40 groups or 560 disabled users), I figured I would draft up a quick powershell to do the work for me.

Write-Host "Importing the ActiveDirectory Module" -foregroundcolor green
Import-Module ActiveDirectory | out-null 
Write-Host "Filtering AD Groups" -foregroundcolor green

#This will filter your groups. Change *changeme* to the group(s) you want filter. Keep the * if you want to wildcard it 
$Groups = (Get-AdGroup -filter * | Where {$_.name -like "*changeme*"} | select Name -expandproperty Name)
Write-Host "Preparing the CSV Template" -foregroundcolor green

#This will create the template for you to export to CSV 
$csv = @() 
$Record = [ordered]@{ 
"Group Name" = "" 
"Name" = "" 
"Username" = "" 
"Enabled" = ""
} 
Write-Host "The Magic is happening. Getting all Disabled Members" -foregroundcolor green

#The Magic
Foreach ($Group in $Groups) 
{ 
 $ArrayOfMembers = Get-ADGroupMember -Identity $Group -Recursive | %{Get-ADUser -Identity $_.distinguishedName -Properties Enabled | ?{$_.Enabled -eq $false}} | Select Name,SamAccountname,Enabled
 foreach ($Member in $Arrayofmembers) 
 {
 $Record."Group Name" = $Group
 $Record."Name" = $Member.Name
 $Record."UserName" = $Member.SamAccountname
 $Record."Enabled" = $Member.Enabled
 $objRecord = New-Object PSObject -property $Record
 $csv += $objrecord
 } 
}

#The Export
Write-Host "Exporting to CSV" -foregroundcolor green
$csv | export-csv "C:\temp\ADSecurityGroups.csv" -NoTypeInformation | out-null
Write-Host "Complete" -foregroundcolor green


The process:

FilterADGroupWithDisabledUsers_step_1
Open powershell as an elevated user
FilterADGroupWithDisabledUsers_step_2
Execute the powershell command. Here you can see it executing and placing an additional CSV file in the path
FilterADGroupWithDisabledUsers_step_3
Open the CSV file with excel. Click Column A > Data > Text to Columns
FilterADGroupWithDisabledUsers_step_5
Click Comma > Finish
FilterADGroupWithDisabledUsers_step_6
Now you have a cool, formatted CSV file.

Download the Powershell script from here.

One Comment

    Richard Draut

    Thanks! This saved a lot of time!

    I ran it like this:

    $Groups = (Get-AdGroup -filter * | Where {$_.name -notlike “*Domain*”} | select Name -expandproperty Name)

    to find any groups containing a disabled user (except for “Domain Users” and “Domain Guests”).

Leave a Reply

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

*
*