Friday, 11 September 2015

Get AD Nested Group Membership with Powershell

This article helps you to understand how to query nested group memberships using powershell. The Microsoft given AD powershell cmdlet Get-ADPrincipalGroupMembership doesn’t provide option to get all the groups part of a nested group membership.

The below powershell command returns only direct memberships of a user.
Get-ADPrincipalGroupMembership "[username]"

Consider the scenario:

  • Consider the user "Smith" is member of the group "DG1".
  • And "DG1" in-turn member of the group "DG2".
  • And "DG2" in-turn member of the group "DG3".
In this case, if you run the above command, you will get only "DG1" as user Smith's membership group. But the user is member of all the three groups ("DG1","DG2","DG3") through nested members hierarchy. To address this need, you can use the below powershell function that helps you to get all direct and indirect membership of a user in Active Directory. This function will recursively enumerate memberships of a given user along with nesting level and parent group information and it will also handle circular membership (infinite loop) problem by holding nested group names in a hashtable.
Import-Module ActiveDirectory

function GetNestedADGroupMembership {
Param([parameter(Mandatory=$true)] $user,
  [parameter(Mandatory=$false)] $grouphash = @{})

   $groups = @(Get-ADPrincipalGroupMembership -Identity $user | select -ExpandProperty distinguishedname)
   foreach ($group in $groups) {
      if ( $grouphash[$group] -eq $null) {
         $grouphash[$group] = $true
         GetNestedADGroupMembership $group $grouphash

GetNestedADGroupMembership 'CN=Smith,OU=TestOU,DC=TestDomain,DC=com'


No comments:

Post a Comment