Get-ADGroupMemberRecursive.ps1

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


<#
 
.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'
 
#>

[CmdletBinding()]
    param (
         [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][string]$DistinguishedName
        ,[String]$ObjectClass = '*'
        ,[string]$Server = (Get-ADForest).SchemaMaster
    )
    Begin {
        [string[]]$UniqueDN = @()
        [string[]]$UniqueGroupSid = @()

        Function _Get-ADGroupMemberRecursive {
                param (
                     [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][string[]]$DistinguishedName
                    ,[string]$Server = (Get-ADForest).SchemaMaster
                )
                Begin {
                    if (!$UniqueGroupSid) {[string[]]$UniqueGroupSid = @()}
                }
                Process {
                    $DistinguishedName | % {
                        $ADObject = Get-ADObject -Identity $_ -Server $Server
                        if ($ADObject.ObjectClass -eq 'group') {
                            $ADGroup = Get-ADGroup -Identity $_ -Server $Server
                            $ADGroupMember = Get-ADGroupMember -Identity $_ -Server $Server
                            if (!$UniqueGroupSid.Contains($ADGroup.SID.Value)) {
                                $UniqueGroupSid += $ADGroup.SID.Value
                                _Get-ADGroupMemberRecursive -DistinguishedName $ADGroupMember -Server $Server
                            } else {
                                Write-Verbose -Message $('Loop Detected: ' + (@($ADGroup.SID.Value,$UniqueGroupSid[-1]) -join ' -> '))
                            }
                        } else {
                            @(Get-ADObject -Identity $ADObject.DistinguishedName -Server $Server)
                        }

                    }
                }
                End {}
        }
    }
    Process {}
    End {
            _Get-ADGroupMemberRecursive -DistinguishedName $DistinguishedName -Server $Server | ? {$_.ObjectClass -like $ObjectClass} | % {
            if (!$UniqueDN.Contains($_.DistinguishedName)) {
                $_; $UniqueDN += $_.DistinguishedName
            }
        }
    }