Often, AD Administrators need to find all members of a given AD group, including nested members. Here is a code snippet that frequently surfaces in examples to solve this puzzle:

$groupname = 'External_Consultants'
$group = Get-ADGroup -Identity $groupname
$dn = $group.DistinguishedName
$all = Get-ADUser -filter {memberof -recursivematch $dn}
$all | Out-GridView

(note that you need the free RSAT tools from Microsoft to be able to use the cmdlets in these samples.)

When you adjust the group name in $groupname to an existing AD group name in your organization, the code does return not just the users that are direct members of this group, but also users that are members in other groups which in turn are members of the given group.

However, the code is very slow. Here is a simpler implementation that is more than five times faster:

$groupname = 'External_Consultants'
$all = Get-ADGroupMember -Identity $groupname -Recursive
$all | Out-GridView

Internally, it makes use of the appropriate LDAP filter and is similar to this direct approach:

$groupname = 'External_Consultants'
$group = Get-ADGroup -Identity $groupname
$dn = $group.DistinguishedName
$ldap = "(memberOf:1.2.840.113556.1.4.1941:=$dn)"
$all = Get-ADUser -LDAPFilter $ldap
$all | Out-GridView

Twitter This Tip! ReTweet this Tip!

Anonymous