-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGet-ADGroupMemberRecursive.ps1
70 lines (70 loc) · 3.34 KB
/
Get-ADGroupMemberRecursive.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#requires -version 2
function Get-ADGroupMemberRecursive {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
Mandatory = $true)]
[Alias("DistinguishedName", "Name", "SamAccountName")]
[String] $Identity,
[Alias("Properties")]
[String[]] $Property = @("DistinguishedName", "Name", "SamAccountName", "DisplayName"),
$Credential = [System.Management.Automation.PSCredential]::Empty)
begin {
Import-Module -Name ActiveDirectory -ErrorAction Stop -Verbose:$false
if ($Credential.Username -match '\S') {
$CredentialSplat = @{
Credential = $Credential
}
}
else {
$CredentialSplat = @{}
}
$Groups = @{}
function Get-ADGroupMemberInternal {
param(
[String] $Identity)
# With Get-ADGroupMember there's a limit of 1000-5000 users by default. Worked around with this, supposedly.
foreach ($Member in @(Get-ADGroup -Identity $Identity -Propert Member @CredentialSplat | Select-Object -ExpandProperty Member | Get-ADObject -Propert $Property @CredentialSplat)) {
Write-Verbose -Message "[$($Member.DistinguishedName)] Processing ..."
if ($Member.ObjectClass -eq 'Group') {
if ($Groups.ContainsKey($Member.DistinguishedName)) {
Write-Verbose -Message "[$($Member.DistinguishedName)] Already processed."
continue # explicit..
}
else {
Write-Verbose -Message "[$($Member.DistinguishedName)] Processing group. Parent group: $Identity."
$Groups[$Member.DistinguishedName] = @()
Get-ADGroupMemberInternal -Identity $Member.DistinguishedName #-ParentGroup $Member.DistinguishedName
}
}
else {
Write-Verbose -Message "[$($Member.DistinguishedName)] Adding non-group element to $Identity array."
if ($Groups.ContainsKey($Identity)) {
$Groups[$Identity] += @($Member |
Add-Member -MemberType NoteProperty -Name DirectParentGroupDN -Value $Identity -PassThru -Force |
Select-Object -Property @(@($Property) + @("DirectParentGroupDN")))
}
}
}
}
}
process {
if (Get-Variable -Name Identity -ErrorAction SilentlyContinue) {
$GrandParentDN = (Get-ADGroup $Identity -ErrorAction SilentlyContinue @CredentialSplat).DistinguishedName
}
elseif ($_) {
$GrandParentDN = (Get-ADGroup $_ -ErrorAction SilentlyContinue @CredentialSplat).DistinguishedName
}
$Groups[$GrandParentDN] = @()
Get-ADGroupMemberInternal -Identity $GrandParentDN
}
end {
$Groups.Values | ForEach-Object {
$_ | Select-Object -Property *, @{ Name = "RootGroupDN"; Expression = { $GrandParentDN } }
}
## DEBUG ##
Write-Verbose -Message "Exporting main data hash to `$Global:STGroupHashTemp."
$Global:STGroupHashTemp = $Groups
}
}