Compare AD Group Memberships with Powershell

Here’s a quick Powershell script I knocked up to help me check AD Group Memberships between two user accounts. Just set the $user1 and $user2 variables and you’re good to go.

?View Code POWERSHELL
Import-Module ActiveDirectory;
 
$user1 = "username1";
$user2 = "username2";
 
$groups1 = Get-ADPrincipalGroupMembership –Identity $user1 | Select-Object -Property Name;
$groups2 = Get-ADPrincipalGroupMembership –Identity $user2 | Select-Object -Property Name;
 
if($groups1.Count -ne $groups2.Count)
{
	Write-Host "The two accounts contain a different number of groups.";
}
 
foreach($group in $groups1)
{
	echo "1 $group";
	if($groups2 -match $group)
	{
		Write-Host "$user1 & $users2 are both members of $group.";
	}
	else
	{
		Write-host "$user2 is not a member of $group";
	}
}
 
# Reverse check
foreach($group in $groups2)
{
	if($groups1 -match $group)
	{
		# No need to reoutput message;
	}
	else
	{
		Write-host "$user1 is not a member of $group";
	}
}

Output will resemble below;

The two accounts contain a different number of groups.
username1 &  are both members of @{Name=Domain Users}.
username2 is not a member of @{Name=AD Group One}
username1 &  are both members of @{Name=VPN Group}.
username2 is not a member of @{Name=Development AD Group}
username2 is not a member of @{Name=SQL Admins Group}
username2 is not a member of @{Name=AD Group Four}

One Comment

  1. Colly says:

    Excellent, been googling for an hour trying to find same, no-ones version as clear cut results as yours.

Leave a Reply