PowerShell Version 2 script to find all empty groups in the domain. This will be groups where the member attribute is empty, and also where no user or computer has the group designated as their primary group.
This can be useful for cleaning up old unused groups. The script first uses the Get-ADGroup cmdlet to retrieve all groups where the member attribute is empty. Next the script checks each of these groups to determine if any users or computers have the group designated as their primary group. Such users and computers are also members of the group. They even show as members in the Active Directory Users and Computers MMC. To do this, the script retrieves the value of the primaryGroupToken attribute of the group. Any user or computer whose primaryGroupID attribute matches this value has the group designated as their primary. Because the primaryGroupToken attribute is operational (also called constructed), special techniques are required to retrieve the value. But the value is the same as the RID (Relative Identifier) of the group, which is the last part of the SID of the object. Since the SID is a default property, it is always retrieved by the Get-ADGroup object. And PowerShell retrieves the value as a friendly string. This makes it is easier to simply parse the SID for the portion after the last dash character. The script uses the Get-ADGroup cmdlet to find all users and computers with a primaryGroupID that matches this RID. Only if no such objects are found does the script output the empty group. The script outputs the Distinguished Name of the group followed by the sAMAccountName in parentheses. The output can be redirected to a text file.
The script supports two optional parameters:
Parameter | Description |
-Security | A switch, so the script only considers security groups. Otherwise, the script considers all groups, including distribution groups. |
-Help | A switch that outputs help information. |
Some usage examples:
Find all empty groups in the domain. Redirect output to a text file.
.\FindEmptyGroups.ps1 > .\Report.txt
Find all empty security groups in the domain.
.\FindEmptyGroups.ps1 -S
Example output:
FindEmptyGroups.ps1
Version 1.0 - November 27, 2016
All empty groups:
Date: 11/25/2016 09:51:55
CN=Contractors,OU=Sales,OU=West,DC=MyDomain,DC=com (ContractorsWest)
CN=Contractors,OU=Sales,OU=East,DC=MyDomain,DC=com (ContractorsEast)
CN=WINS Users,CN=Users,DC=MyDomain,DC=com (WINS Users)
CN=DnsAdmins,CN=Users,DC=MyDomain,DC=com (DnsAdmins)
Total number of empty groups: 4
You should review the output before deleting any empty groups found to make sure they are no longer needed. Some can be default groups, like the last two in the example output above. These might be needed in the future. Also, it is recommended that you have the AD Recycle Bin enabled before deleting any groups. This allows you to recover the groups if necessary.
FindEmptyGroups.txt <<-- Click here to view or download the program