September 5, 2014

PowerShell: Compare Membership Of Two Active Directory Groups

At my company we have a web filtering solution (McAfee Web Protection) where we use Active Directory groups assigned to specific web filtering policies. Even though these groups are not supposed to have duplicate user accounts, over time, with multiple people administering them, that is exactly what has occurred. I needed a quick way to compare membership between two groups so that I could remove these duplicate users. The PowerShell command below will do just that. It will look at two Active Directory groups, find the “SamAccountName” attribute for each user account, then display a list showing you the users in each group, including dual memberships.

diff (Get-ADGroupMember "Group 1") (Get-ADGroupMember "Group 2") -Property 'SamAccountName' -IncludeEqual

Here’s an example of the results you will get from the above command:

SamAccountName SideIndicator
-------------- -------------
USER1          ==
USER2          =>
USER3          =>
USER4          =>
USER5          <=
USER6          <=

== This user is in both groups.
=> This user is in the second group.
<= This user is in the first group.

It’s important that you add the “-IncludeEqual” parameter as that is required to show you the users who have membership in both groups (==).

Please share your thoughts