Recursive group Membership in Powershell

In this post I will show an easy way to get the recursive group membership for the current user.

I use this in a logon script to handle certain tasks based on group membership.

Most scripts I see for this task do a manual recursive enumeration but in a large environment this could be very slow.

A better way would be to use the tokenGroups attribute of the Active Directory user object.

The tokenGroups attribute is an array of SIDs computed by Active Directory and is used to verify user access.

We need to translate these SIDs to their sAMAccountNames to get the actual group names.

In unmanaged code this could be accomplished by calling the DsCrackNames API or the IADsNameTranslate interface.

In Powershell the easiest way is to use the UserPrincipal class (requires .NET Framework 3.5 or higher) which exposes the GetAuthorizationGroups method.

This makes it a very easy task. In the sample below I also use the where object to filter the results and the select object to return only the SamAccountName property.

Leave a Reply

  1. Pingback: Tweets die vermelden Recursive group Membership in Powershell | Remko Weijnen's Blog (Remko's Blog) --

  2. Pingback: Recursive Groups #2 | Remko Weijnen's Blog (Remko's Blog)

  3. Excellent work! Much more efficient than what I had cobbled together so far (old code was more than 41 lines just to return a group membership array). Thank you!

  4. For those who want to do it for any user:

    $name = “arosen” #SamAccountName

    $assembly = [System.Reflection.Assembly]::LoadWithPartialName(“System.DirectoryServices.AccountManagement”)
    $context = New-Object -typename “System.DirectoryServices.AccountManagement.PrincipalContext” -argumentlist $([System.DirectoryServices.AccountManagement.ContextType]::Domain)
    $user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($context,$([System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName),$name)
    $user.GetAuthorizationGroups() | select SamAccountName