#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.

Share on: