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
71
72
73
74
75
76
77

<#PSScriptInfo
 
.VERSION 1.0.0
 
.GUID d79645d6-b49c-47d7-a433-1fb2044d2b91
 
.AUTHOR saw-friendship
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS
 ActiveDirectory ADGroupMemberRecursive ADGroup Member ADUser Search
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
#>


<#
 
.DESCRIPTION
 Recursive search all users in contains group
 
.EXAMPLE
Get-ADGroup 'Domain Admins' | Get-ADGroupMemberRecursive
 
.EXAMPLE
Get-ADGroupMemberRecursive (Get-ADGroup 'Domain Admins')
 
.EXAMPLE
Get-ADGroupMemberRecursive 'CN=Domain Admins,OU=Groups,DC=contoso,DC=com'
 
#>
 

param (
    [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
    [string[]]$DistinguishedName,
    [switch]$Unique
)
Begin {
    if ($Unique) {$SelectParam = @{'Unique' = $true}}
    if (! $UniqueGroupSid.Count) {[array]$UniqueGroupSid = @()}
}
Process {
    $DistinguishedName | % {
        $ADObject = Get-ADObject -Identity $_
        if ($ADObject.ObjectClass -eq 'group') {
            $ADGroup = Get-ADGroup -Identity $_ -Properties Member
            if (!$UniqueGroupSid.Contains($ADGroup.SID.Value)) {
                $UniqueGroupSid += $ADGroup.SID.Value
                Get-ADGroupMemberRecursive -DistinguishedName @($ADGroup.Member.ForEach({Get-ADObject -Identity $_}))
            } else {
                Write-Warning $('Loop Detected: ' + (@($ADGroup.SID.Value,$UniqueGroupSid[-1]) -join ' -> '))
            }
        } elseif ($ADObject.ObjectClass -eq 'user') {
            @(Get-ADUser -Identity $ADObject.DistinguishedName)
        } else {}
        
    } | Select-Object @SelectParam
}
End {}