Powershell – Compare the group memberships of two Active Directory (AD) accounts

Compare Group Memberships by SamAccountName:
You can compare the group memberships of two users by their SamAccountName attribute.
Here’s an example PowerShell command that displays a list of users in each group, including dual memberships:

diff (Get-ADGroupMember "User1") (Get-ADGroupMember "User2") -Property 'SamAccountName' -IncludeEqual

Replace “User1” and “User2” with the actual SamAccountNames of the AD accounts you want to compare.

Custom Function for Group Comparison:
If you prefer a more detailed comparison, you can create a custom function.
Here’s a sample function that compares two user accounts in Active Directory and tells you their group membership similarities and differences:

function Get-PWADGroupComparison {
    # Compare group memberships of two users
    param (
        [string]$User1,
        [string]$User2
    )
    $Groups1 = (Get-ADPrincipalGroupMembership $User1 | Select-Object -ExpandProperty Name)
    $Groups2 = (Get-ADPrincipalGroupMembership $User2 | Select-Object -ExpandProperty Name)
    $CommonGroups = Compare-Object -ReferenceObject $Groups1 -DifferenceObject $Groups2 -IncludeEqual
    Write-Output "Common Groups:"
    $CommonGroups | Where-Object { $_.SideIndicator -eq "==" } | ForEach-Object { Write-Output $_.InputObject }
    Write-Output "Unique Groups for $User1:"
    $CommonGroups | Where-Object { $_.SideIndicator -eq "<=" } | ForEach-Object { Write-Output $_.InputObject }
    Write-Output "Unique Groups for $User2:"
    $CommonGroups | Where-Object { $_.SideIndicator -eq "=>" } | ForEach-Object { Write-Output $_.InputObject }
}

You can use this function by calling:

Get-PWADGroupComparison -User1 "User1" -User2 "User2"

Leave a Reply

Your email address will not be published. Required fields are marked *