Last active
December 18, 2015 19:19
-
-
Save pepoluan/5832392 to your computer and use it in GitHub Desktop.
Get-Ancestors : recursively gets all groups in which an Active Directory object is a member of (directly or indirectly). It returns an array of Active Directory objects. NOTE: ActiveRoles is REQUIRED.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Get-Ancestors() { | |
# The [switch] decorator allows specifying parameters as a flag | |
param( | |
$Identity, | |
[switch]$Silent, | |
[switch]$IncludeAllProperties | |
) | |
# Initialize the hashtable and the .Net Queue | |
$Ancestors = @{} | |
$Queue = New-Object System.Collections.Queue | |
Function getParents($d) { | |
# The -IncludeAllProperties switch of ActiveRoles Shell *totally* ignore | |
# whatever value we assign to it (e.g., specifying "-IncludeAllProperties:false" | |
# will result in identical result as specifying "-IncludeAllProperties". | |
# That is why we need to 'build' the parameter set | |
$params = @{ Identity = $d } | |
If ($IncludeAllProperties) { $params += @{ IncludeAllProperties = $True } } | |
$parents = Get-QADMemberOf @params | |
ForEach ($p in $parents) { | |
If (! $Ancestors.ContainsKey($p.DN) ) { | |
If (! $Silent) { Write-Host "." -NoNewLine } | |
$Ancestors.Add($p.DN,$p) | |
$Queue.Enqueue($p) | |
} | |
} | |
} | |
$o = $Identity | |
Do { | |
getParents $o | |
If ($Queue.Count -ge 1) { $o = $Queue.Dequeue() } | |
Else { Break } | |
} | |
Until ($false) | |
Write-Host "" | |
# The type of $Ancestors.Values is ValueCollection, we flatten it to an | |
# array to simplify further processing. For example: If you want to get the | |
# n-th member of the result, you can simply wrap this function's | |
# incantations in parens ( ) and specify an array index. E.g. : | |
# (Get-Ancestors username)[2] | |
@( $Ancestors.Values ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment