Advertisement
Pavix

Get-ADUserNestedGroups.ps1

Mar 29th, 2023
936
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 1.46 KB | Software | 0 0
  1. param
  2.   (
  3.     [string]$StrUser
  4.   )
  5.  
  6.  
  7. #Get all recursive groups a user belongs.
  8. Function Get-ADUserNestedGroups
  9. {
  10.     Param
  11.     (
  12.         [string]$DistinguishedName,
  13.         [array]$Groups = @()
  14.     )
  15.  
  16.     #Get the AD object, and get group membership.
  17.     $ADObject = Get-ADObject -Filter "DistinguishedName -eq '$DistinguishedName'" -Properties memberOf, DistinguishedName;
  18.    
  19.     #If object exists.
  20.     If($ADObject)
  21.     {
  22.         #Enummurate through each of the groups.
  23.         Foreach($GroupDistinguishedName in $ADObject.memberOf)
  24.         {
  25.             #Get member of groups from the enummerated group.
  26.             $CurrentGroup = Get-ADObject -Filter "DistinguishedName -eq '$GroupDistinguishedName'" -Properties memberOf, DistinguishedName;
  27.        
  28.             #Check if the group is already in the array.
  29.             If(($Groups | Where-Object {$_.DistinguishedName -eq $GroupDistinguishedName}).Count -eq 0)
  30.             {
  31.                 #Add group to array.
  32.                 $Groups +=  $CurrentGroup;
  33.  
  34.                 #Get recursive groups.      
  35.                 $Groups = Get-ADUserNestedGroups -DistinguishedName $GroupDistinguishedName -Groups $Groups;
  36.             }
  37.         }
  38.     }
  39.  
  40.     #Return groups.
  41.     Return $Groups;
  42. }
  43.  
  44.  
  45. #Get all groups.
  46. $Groups = Get-ADUserNestedGroups -DistinguishedName (Get-ADUser -Identity $StrUser).DistinguishedName;
  47.  
  48. #Output all groups.
  49. $Groups | Select-Object Name | Sort-Object -Property Name;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement