KB10110 - PS: Get AD Group Membership Recursive

General description

This article contains a Power Shell one liner to receive an ADDS users groupmembership recursive without using Quest implementation.

When you execute the line it asks you for the username and then displays all groups a users belongs to recursive. The yellow groups are groups the user has a direct membership.


Script code:

	
##One Liner
Import-Module ActiveDirectory;$global:IndirectCounter = 0; $DirectCounter = 0; Function Get-IndirectGoups ($GroupDN) {Get-ADGroup -Identity "$GroupDN" -Properties MemberOf | Select-Object -ExpandProperty MemberOf | ForEach-Object {$global:IndirectCounter++;Write-Host $_; Get-IndirectGoups -GroupDN $_}} ; Get-ADUser (Read-Host -Prompt "Username") -Properties MemberOf | Select-Object -ExpandProperty MemberOf | ForEach-Object { $DirectCounter++;Write-Host -Foregroundcolor yellow $_ ; Get-IndirectGoups -GroupDN $_ };Write-Host "------";Write-Host -ForegroundColor Green "Total direct groups: " -NoNewline; Write-Host ($DirectCounter);Write-Host -ForegroundColor Green "Total indirect groups: " -NoNewline; Write-Host ($global:IndirectCounter);Write-Host -ForegroundColor Green "Total groups: " -NoNewline; Write-Host -ForegroundColor Yellow ($global:IndirectCounter + $DirectCounter)

## The same one in readable ;-)
Import-Module ActiveDirectory
$global:IndirectCounter = 0
$DirectCounter = 0

Function Get-IndirectGoups ($GroupDN) {
	Get-ADGroup -Identity "$GroupDN" -Properties MemberOf | `
		Select-Object -ExpandProperty MemberOf | `
		ForEach-Object {
			$global:IndirectCounter++
			Write-Host $_
			Get-IndirectGoups -GroupDN $_
		}
} 

Get-ADUser (Read-Host -Prompt "Username") -Properties MemberOf | `
	Select-Object -ExpandProperty MemberOf | `
	ForEach-Object { 
		$DirectCounter++
		Write-Host -Foregroundcolor yellow $_ 
		Get-IndirectGoups -GroupDN $_ 
	}

Write-Host "------"
Write-Host -ForegroundColor Green "Total direct groups: " -NoNewline
Write-Host ($DirectCounter)
Write-Host -ForegroundColor Green "Total indirect groups: " -NoNewline
Write-Host ($global:IndirectCounter)
Write-Host -ForegroundColor Green "Total groups: " -NoNewline
Write-Host -ForegroundColor Yellow ($global:IndirectCounter + $DirectCounter)
	

>> syntax highlighting powered by highlight.js