How to get all groups that a user is a member of?

后端 未结 30 1779
攒了一身酷
攒了一身酷 2020-12-04 05:56

PowerShell\'s Get-ADGroupMember cmdlet returns members of a specific group. Is there a cmdlet or property to get all the groups that a particular user is a member of?

30条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 06:34

    Studying all comments presented gave me a starting point (thanks for such) but left me with several unresolved issues. As result here is my answer. The code snippet provided does a little more than what is asked for but it provides helpful debugging info.

    [array] $script:groupsdns = @()
    function Get-ADPrincipalGroupMembershipRecursive() 
    {
      Param( [string] $dn, [int] $level = 0, [array] $groups = @() )
    
      #if(($groupsdns | where { $_.DistinguishedName -eq $dn }).Count -ne 0 ) { return $groups } # dependency on next statement
      #$groupsdns += (Get-ADObject $dn -Properties MemberOf) # Get-ADObject cannot find an object with identity
      if ($script:groupsdns.Contains($dn)) { return $groups }
      $script:groupsdns += $dn
      $mo = $Null
      $mo = Get-ADObject $dn -Properties MemberOf # Get-ADObject cannot find an object with identity
      $group = ($dn + " (" + $level.ToString())
      if ($mo -eq $Null) { $group += "!" }
      $group += ")"
      $groups += $group
      foreach( $groupdn in $mo.MemberOf )
      {
        $groups = Get-ADPrincipalGroupMembershipRecursive -dn $groupdn -level ($level+1) -groups $groups
      }
      if ($level -le 0) 
      { 
        $primarygroupdn = (Get-ADUser -Identity $dn -Properties PrimaryGroup).PrimaryGroup 
        $groups = Get-ADPrincipalGroupMembershipRecursive -dn $primarygroupdn -level ($level+1) -groups $groups
      }
      return $groups
    }
    $adusergroups = Get-ADPrincipalGroupMembershipRecursive -dn $aduser.DistinguishedName
    $adusergroups | ft -AutoSize | `
                  Out-File -Width 512 Get-ADPrincipalGroupMembershipRecursive.txt #-Append #-Wrap # | Sort-Object -Property Name
    

提交回复
热议问题