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

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

    To get it recursive, you can use:

    <# 
        .SYNOPSIS   
            Get all the groups that a user is MemberOf.
    
        .DESCRIPTION
            This script retrieves all the groups that a user is MemberOf in a recursive way.
    
        .PARAMETER SamAccountName
            The name of the user you want to check #>
    
    Param (
        [String]$SamAccountName = 'test',
        $DomainUsersGroup = 'CN=Domain Users,CN=Users,DC=domain,DC=net'
    )
    
    
    Function Get-ADMemberOf {
        Param (
            [Parameter(ValueFromPipeline)]
            [PSObject[]]$Group,
            [String]$DomainUsersGroup = 'CN=Domain Users,CN=Users,DC=grouphc,DC=net'
        )
        Process {
            foreach ($G in $Group) {
                $G | Get-ADGroup | Select -ExpandProperty Name
                Get-ADGroup $G -Properties MemberOf| Select-Object Memberof | ForEach-Object {
                    Get-ADMemberOf $_.Memberof
                }
            }
        }
    }
    
    
    $Groups = Get-ADUser $SamAccountName -Properties MemberOf | Select-Object -ExpandProperty MemberOf
    $Groups += $DomainUsersGroup
    $Groups | Get-ADMemberOf | Select -Unique | Sort-Object
    

提交回复
热议问题