A PowerShell script to find all empty groups in the domain. 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:
    -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

Note: The first one (or several) letters of each parameter can be used as aliases.

Some usage examples:

.\FindEmptyGroups.ps1 > .\Report.txt 
    Find all empty groups in the domain. Redirect output to a text file. 
.\FindEmptyGroups.ps1 -S 
    Find all empty security groups in the domain. 
 Example output:
Version 1.0 - November 272016 
All empty groups: 
Date11/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.