| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 | Param(    [string]$DistinguishedName,    [string]$UserIdentity = "",    [array]$Groups = @(),    [switch]$Duplicates)if ($UserIdentity -notin @($null, "")){    $DistinguishedName = (Get-ADUser -Identity $UserIdentity).distinguishedname}#The user to check.# $User = "max.mustermann@domain.com"; #Get all groups.# $Groups = Get-ADUserNestedGroups -DistinguishedName (Get-ADUser -Identity $User).DistinguishedName;#Output all groups.# $Groups | Select-Object Name | Sort-Object -Property Name;#Get the AD object, and get group membership.$ADObject = Get-ADObject -Filter "DistinguishedName -eq '$DistinguishedName'" -Properties memberOf, DistinguishedName;#If object exists.If($ADObject){    #Enummurate through each of the groups.    Foreach($GroupDistinguishedName in $ADObject.memberOf)    {        #Get member of groups from the enummerated group.        $CurrentGroup = Get-ADObject -Filter "DistinguishedName -eq '$GroupDistinguishedName'" -Properties memberOf, DistinguishedName;            #Check if the group is already in the array.        If(($Groups | Where-Object {$_.DistinguishedName -eq $GroupDistinguishedName}).Count -eq 0)        {            #Add group to array.            $Groups +=  [PSCustomObject]@{                DistinguishedName=$CurrentGroup.DistinguishedName                Name=$CurrentGroup.Name                ObjectClass=$CurrentGroup.ObjectClass                Parent=$DistinguishedName            };            #Get recursive groups.                  $Groups = &$PSCommandPath -DistinguishedName $GroupDistinguishedName -Groups $Groups;        } elseif ($Duplicates) {            "Duplicate: $($CurrentGroup.DistinguishedName)" | Out-Host        }    }}#Return groups.$Groups;
 |