• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
OpenTechTips

OpenTechTips

Short and Concise Guides for IT Professionals

MENUMENU
  • HOME
  • ALL TOPICS
    • Active Directory
    • Exchange
    • InfoSec
    • Linux
    • Networking
    • Scripting
      • PowerShell
    • SSL
    • Virtualization
    • Web
    • Tools
  • ABOUT
  • SUBSCRIBE
Home » How to Export Users from Nested AD Groups

How to Export Users from Nested AD Groups

October 17, 2020 - by Zsolt Agoston - last edited on October 18, 2020

In a real-life IT environment, it is inevitable to have nested groups, one containing another, which contains another, etc.

To get all the users who are members of those groups, the following GetADGroup function will help us. It displays all the member users, no matter how deep the nested structure goes.

# GetADGroup

<#
Script to retrieve the members of specified groups, checking the nested members, removing duplicates
#>

function GetADGroup {
param ( [string]$Member )
 
$members = @()
Get-ADGroupMember $Member | %{
               if ($_.objectClass -eq "group") { GetADGroup -Member $_.distinguishedName
               } else { $members += $_.name }
}
$result = ($members | Sort -Unique)
 
return $result
}
 
# Example: getting the members of the group called "All Users"
GetADGroup -Member "All Users" | Sort -Unique

# Example: export user list to a csv file
$group = "All Users"
GetADGroup -Member $group | Sort -Unique | % { [pscustomobject]@{"Group" = $group; "Member" = $_} | Export-Csv "$group members.csv" -Append -NoTypeInformation}

Example - Export "All Users"

In our test system we have three AD groups nested in each other, all of them contain a certain number of users. On the top of that, Alice user is a member of all three groups. See the diagram below:

How to Export Users from Nested AD Groups

After running the query, here is the result:

How to Export Users from Nested AD Groups

Reader Interactions

Community Questions Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Tools

Secondary Sidebar

CONTENTS

  • # GetADGroup
  • Example – Export “All Users”

  • Terms of Use
  • Disclaimer
  • Privacy Policy