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.