Get-ADUserNestedGroups.ps1 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. Param
  2. (
  3. [string]$DistinguishedName,
  4. [string]$UserIdentity = "",
  5. [array]$Groups = @(),
  6. [switch]$Duplicates
  7. )
  8. if ($UserIdentity -notin @($null, "")){
  9. $DistinguishedName = (Get-ADUser -Identity $UserIdentity).distinguishedname
  10. }
  11. #The user to check.
  12. # $User = "max.mustermann@domain.com";
  13. #Get all groups.
  14. # $Groups = Get-ADUserNestedGroups -DistinguishedName (Get-ADUser -Identity $User).DistinguishedName;
  15. #Output all groups.
  16. # $Groups | Select-Object Name | Sort-Object -Property Name;
  17. #Get the AD object, and get group membership.
  18. $ADObject = Get-ADObject -Filter "DistinguishedName -eq '$DistinguishedName'" -Properties memberOf, DistinguishedName;
  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. #Check if the group is already in the array.
  28. If(($Groups | Where-Object {$_.DistinguishedName -eq $GroupDistinguishedName}).Count -eq 0)
  29. {
  30. #Add group to array.
  31. $Groups += [PSCustomObject]@{
  32. DistinguishedName=$CurrentGroup.DistinguishedName
  33. Name=$CurrentGroup.Name
  34. ObjectClass=$CurrentGroup.ObjectClass
  35. Parent=$DistinguishedName
  36. };
  37. #Get recursive groups.
  38. $Groups = &$PSCommandPath -DistinguishedName $GroupDistinguishedName -Groups $Groups;
  39. } elseif ($Duplicates) {
  40. "Duplicate: $($CurrentGroup.DistinguishedName)" | Out-Host
  41. }
  42. }
  43. }
  44. #Return groups.
  45. $Groups;