Determine the logged-on User’s AD group membership in PowerShell

I came across this great little gold nugget of a 1-liner while reading this blog post on automating Outlook Profile creation, so all props go to Travis Runyard for this one.


To break it down, this is using the [ADSISEARCHER] type accelerator to create an instance of the DirectorySearcher class.

The string specified directly after the accelerator denotes the search filter, so in this case, we’ll only be searching for objects with a samaccountname attribute that matches the current user’s logon name.

There’s only ever going to be one object returned, so we use the FindOne method to return a single System.DirectoryServices.SearchResult object.

All that’s left after that, is to get the contents of the “memberof” property on that object.

In his blog post, Travis goes one step farther and uses a regex to remove the LDAP path elements like “CN=” which leaves us with just the group names. Very smart!

([ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.memberof -replace '^CN=([^,]+).+$','$1'

If we store the results of this search in a variable, for example $userGroups, we can then check if the user is a member of a certain group:

Alternatively, you could use comparison operators like –contains, –ccontains for a case-sensitive comparison, or even –notcontains.

([ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.memberof -replace '^CN=([^,]+).+$','$1' -ccontains "Colour Printing"

4 thoughts on “Determine the logged-on User’s AD group membership in PowerShell

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s