Compare AD Group Membership Between Two Users in Powershell

Posted by

I’ve come to notice that some companies leverage Active Directory groups for certain security policies. Conceptually, it works out to be “any user in this group gets this access”. I won’t speak to best practices surrounding this concept, but with manual assignments of individual users to individual groups, there can be a gap when users are onboarded or there are job changes. Often times, there’s an existing user whose group membership should be mimicked for the new user.

Background

With Powershell, you can query Active Directory directly, as long as you have the proper modules installed and imported. Taken from this stack overflow question, to install the require module:

  • Open Control Panel -> Programs and Features -> Turn On/Off Windows Features
  • Find “Remote Server Administration Tools” and expand it
  • Find “Role Administration Tools” and expand it
  • Find “AD DS And AD LDS Tools” and expand it
  • Check the box next to “Active Directory Module For Windows PowerShell”.
  • Click OK and allow Windows to install the feature

Then, to Import the module into a powershell instance, simply run the command

import-module activedirectory

Group Comparison

Now that you have everything you need, you can actually perform our comparison of groups. By leveraging the Get-AdPrincipalGroupMembership command, you can run a compare object between the two users group membership names. Below is the script I came up with. For clarity, I also added in a sort-object on the name property.

Compare-Object -ReferenceObject (Get-AdPrincipalGroupMembership newUser | select name | sort-object -Property name) -DifferenceObject (Get-AdPrincipalGroupMembership existingUser | select name | sort-object -Property name) -property name -passthru 

The output will look something like the following:

Using Powershell might not be the ideal way to manage an Active Directory instance, but it’s a pretty quick and lightweight way to perform a basic lookup. I have mostly used powershell with Active Directory for simple group membership (IE, is a certain user in a certain group), but using built in commands like compare-object as described can produce some very powerful information.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.