Skip to content

Instantly share code, notes, and snippets.

@pepoluan
Last active December 18, 2015 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pepoluan/5832392 to your computer and use it in GitHub Desktop.
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.
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