In this post we’ll explore how to discover empty groups in Active Directory. Empty groups are groups that have no members. Obviously, if this condition does not change for a while you might want to consider deleting those groups.
First, lets see how this can be done in ADUC. If you are familiar with custom searches here is a simple LDAP filter that will do the trick:
(&(objectCategory=Group)(!member=*))
The problem with ADUC is that you can’t easily select a set of fields you would want to see for each group. This makes it difficult, for instance, to see which of those groups have not been changed for a long time.
This is where PowerShell comes in handy. .
Thanks to the Active Directory module for PowerShell introduced for Windows Server 2008 R2 and later identifying empty groups is a matter of two command:
PS C:> $last = (Get-Date) – (new-timespan -days 90)
PS C:> get-adgroup -SearchScope Subtree -SearchBase “DC=toronto,DC=local” -Properties whenChanged -filter {(member -notlike “*”) -and (whenChanged -le $last)} | select-object -property distinguishedName, whenChanged | export-csv c:testemptygroups.csv
In the PowerShell code above we do the following:
1. Set the $last variable to 90 days ago.
2. Find groups with no members using the same filter in a correct syntax expected by the Get-ADGroup cmdlet:
(member -notlike “*”)
3. Check the last changed date of each found group and leave only those that have not been changed within the last 90 days:
(whenChanged -le $last)
4. Select the properties we want to see for each resulting group:
select-object -property distinguishedName, whenChanged
5. Save a list of groups into a csv file:
export-csv c:testemptygroups.csv
This simple enough PowerShell script can be a huge time savior and it gives the right results with one exception. It does not factor in primary groups.
Primary groups do not store members in its member attribute. Instead their membership is calculated based on the backlink stored in the user object that is included into that group. So, if all users in a group have this group listed as their primary group than the actual member attribute will appear empty and such group will be picked up by the script above. Usually this is the case with built-in group Domain Users. You might want to handle such cases as an exception.
<< Active Directory User and Group Reporting: A practical guide for administrators