Skip to content

Instantly share code, notes, and snippets.

@tijme
Last active February 20, 2023 11:52
Show Gist options
  • Save tijme/28de9cbd70fb184643e2bdc2803d4613 to your computer and use it in GitHub Desktop.
Save tijme/28de9cbd70fb184643e2bdc2803d4613 to your computer and use it in GitHub Desktop.
This function will return all domain users in the specified group, including recursive memberships. This also includes users in special groups such as the "Domain Users" group. Users are part of special groups via the SID instead of the members attribute. Therefore `Get-ADGroupMembers -Recursive` doesn't return users in these special groups.
Function Get-AllADGroupUsersRecursively {
<#
.SYNOPSIS
This script will identify all AD users in a specific group recursively (including special groups such as "Domain Users").
.DESCRIPTION
This script will identify all AD users in a specific group recursively (including special groups such as "Domain Users").
.NOTES
Name: Get-AllADGroupUsersRecursively
Author: Tijme Gommers
Version: 1.0
DateCreated: 05/31/2021
.PARAMETER Group
The group name to start searching in
.EXAMPLE
Get-AllADGroupUsersRecursively HR_Department_Network_Share
.LINK
https://twitter.com/tijme
#>
[CmdletBinding()]
Param(
[Parameter(
Mandatory = $True,
HelpMessage = "Specify the group name to start searching in",
ValueFromPipeline = $True,
ValueFromPipelineByPropertyName = $True,
Position = 0
)] [ValidateNotNullOrEmpty()] [string] $Group
)
Begin {
$groupsHT = @{} # Parsed groups hashtable
$usersHT = @{} # Parsed users hashtable
if ($Group -is [String]) {
$Group = Get-ADGroup $Group
}
}
Process {
if($groupsHT.Contains($Group) -eq $true) {
return
}
$groupsHT.Add($Group, 1)
$members = Get-ADGroupMember $Group
foreach($member in $members) {
if ($member.objectClass -eq "group") {
Get-AllADGroupMemberRecursively $member
} else {
$usersHT.Add($member, 1)
}
}
}
End {
return $usersHT.Keys
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment