Advertisement
Yevrag35

GetNestedMembership

Aug 6th, 2020
2,047
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function Get-NestedMembership {
  2.  
  3.     [CmdletBinding()]
  4.     param (
  5.         [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
  6.         [object[]] $InputObject
  7.     )
  8.  
  9.     Begin {
  10.         $users = New-Object System.Collections.Generic.List[object]
  11.  
  12.         #region INNER FUNCTION
  13.         Function getRecursiveMembers {
  14.             param (
  15.                 [System.Collections.Generic.HashSet[string]]$Processed,
  16.                 [string]$DistinguishedName
  17.             )
  18.  
  19.             $users = New-Object 'System.Collections.Generic.List[object]'
  20.  
  21.             $ldapFilter = "(memberOf=$DistinguishedName)"
  22.             [array] $objs = Get-ADObject -LDAPFilter $ldapFilter
  23.  
  24.             foreach ($member in $objs) {
  25.                 if ($member.ObjectClass -eq "group" -and $Processed.Add($member.DistinguishedName)) {
  26.  
  27.                     $innerResult = getRecursiveMembers -Processed $Processed -DistinguishedName $member.DistinguishedName
  28.                     $Processed.UnionWith($innerResult.Processed)
  29.                     $users.AddRange($innerResult.Users)
  30.  
  31.                 }
  32.                 else {
  33.                     $member.psobject.Properties.Add((New-Object PSNoteProperty("FromGroup", $DistinguishedName)))
  34.                     $users.Add($member)
  35.                 }
  36.             }
  37.  
  38.             [pscustomobject]@{
  39.                 Users     = $users
  40.                 Processed = $Processed
  41.             }
  42.         }
  43.         #endregion
  44.     }
  45.  
  46.     Process {
  47.         foreach ($group in $InputObject) {
  48.  
  49.             $processed = New-Object System.Collections.Generic.HashSet[string] -ArgumentList 1
  50.             [void] $processed.Add($group.DistinguishedName)
  51.  
  52.             $result = getRecursiveMembers -Processed $processed -DistinguishedName $group.DistinguishedName
  53.  
  54.             foreach ($u in $result.Users) {
  55.                 $u.psobject.Properties.Add((New-Object PSNoteProperty("MemberOf", $group.Name)))
  56.             }
  57.  
  58.             $users.AddRange($result.Users)
  59.         }
  60.     }
  61.     End {
  62.         $users
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement