#PSTip Retrieve group membership of an Active Directory group recursively

Note: This tip requires PowerShell 2.0 or above.

When you need to manage Active Directory, the Active Directory PowerShell module is the first admin choice as it provides many cmdlets for administering and interfacing with various AD objects. For example, to get the members of an AD group you’d use the Get-ADGroupMember cmdlet. But what do you do when the AD module is not available in your environment?

Starting with .NET 3.5 you can load the System.DirectoryServices.AccountManagement assembly and use its classes and types to get the members of the group. With the following snippet you can get all members of an AD group, including nested members.

$Recurse = $true
$GroupName = 'Domain Admins'
Add-Type -AssemblyName System.DirectoryServices.AccountManagement

# use the 'Machine' ContextType if you want to retrieve local group members
# for possible values of the numeration, visit
# http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.contexttype.aspx
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$group = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($ct,$GroupName)

One important thing to keep in mind, the returned collection does not contain group objects when the recursive flag is set to true.

Filed in: Columns, Tips and Tricks Tags: , ,

5 Responses to "#PSTip Retrieve group membership of an Active Directory group recursively"

  1. DVS says:


    Is [asdi] the same thing as the System.DirectoryServices.AccountManagement assembly?

    • ShayLevy says:

      ADSI is a shortcut to System.DirectoryServices.DirectoryEntry and is available natively in all versions of PowerShell. The AccountManagement asembly shipped with .NET 3.5 and you need to explicitly load it. Anyway, to see the full type name of a type shortcut: [adsi].FullName

  2. aenagy says:

    How would you query in a different (trusted) domain?

Leave a Reply

Submit Comment

© 8341 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: