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

后端 未结 30 1749
攒了一身酷
攒了一身酷 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:41

    I wrote a PowerShell function called Get-ADPrincipalGroupMembershipRecursive. It accepts the DSN of a user, computer, group, or service account. It retrieves an initial list of groups from the account's memberOf attribute, then recursively checks those group's memberships. Abbreviated code is below. Full source code with comments can be found here.

    function Get-ADPrincipalGroupMembershipRecursive( ) {
    
        Param(
            [string] $dsn,
            [array]$groups = @()
        )
    
        $obj = Get-ADObject $dsn -Properties memberOf
    
        foreach( $groupDsn in $obj.memberOf ) {
    
            $tmpGrp = Get-ADObject $groupDsn -Properties memberOf
    
            if( ($groups | where { $_.DistinguishedName -eq $groupDsn }).Count -eq 0 ) {
                $groups +=  $tmpGrp           
                $groups = Get-ADPrincipalGroupMembershipRecursive $groupDsn $groups
            }
        }
    
        return $groups
    }
    
    # Simple Example of how to use the function
    $username = Read-Host -Prompt "Enter a username"
    $groups   = Get-ADPrincipalGroupMembershipRecursive (Get-ADUser $username).DistinguishedName
    $groups | Sort-Object -Property name | Format-Table
    

提交回复
热议问题