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:
After running the query, here is the result:
Comments