#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)
$group.GetMembers($Recurse)

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

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts

%d bloggers like this: