PowerShell for Windows Admins

Dec 3 2012   4:58PM GMT

Comparing group membership

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

A question on the forum asked about comparing the memberships of two groups & displaying information about the users that are in both. The normal reaction is that you have to iterate through the two groups but then I remembered Compare-Object and came up with this

$group1 = Get-ADGroupMember -Identity ADL-group1 | select SamAccountName            
$group2 = Get-ADGroupMember -Identity ADL-group2 | select SamAccountName            
Compare-Object -ReferenceObject $group1 -DifferenceObject $group2 -IncludeEqual |             
where SideIndicator -eq "==" |            
foreach {            
 $sam = ($_.InputObject).SamAccountName             
 Get-ADUser -Identity $sam -Properties *            

Get the group membership of each group into a variable – I’m using the Microsoft cmdlets and just selecting the samaccountname to compare.

Using Compare-Object I used the –IncludeEqual parameter to make sure I got the matches and then filtered on the SideIndicator value of “==” .  That gets me the matches.

I then loop through them and use Get-ADUser to pull back the properties I need.

If you want to do this with the quest cmdlets use distinguished name instead of samaccountname

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: