首页 > 解决方案 > Get all Groups of a user/group recursively

问题描述

I have some code to get the groups of a user and write them down into an Arraylist, however ît will only find the groups where a user is directly in. It won't find groups deeper then 1 level.

For example: User is member of Group 1, Group 1 is member of Groups 2, etc. I will only find Group 1. Group 2 won't be written down into my ArrayList.

$Groups = Get-ADPrincipalGroupMembership -Server ESX-DC $GroupName

$GroupArrayList = New-Object System.Collections.ArrayList
foreach ($Group in $Groups)
{
$GroupArrayList.Add($Group.Name) | Out-Null 
} 

Can someone provide me some help here? Thanks.

标签: powershellactive-directoryusergroups

解决方案


我不知道递归参数,所以我认为您必须自己编写。然而,我为类似的任务编写了一个脚本。可能会有所帮助。

function Get-ADPrincipalGroupMembershipRecurse
{
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]$Identity   
    )

    $script:Groups = @()

    function Get-NestedAdGroups
    {
        param
        (
            [Parameter(Mandatory = $true)]
            [System.String]$Identity   
        )

        $ADGroup = Get-ADGroup -Identity $Identity -Properties MemberOf, Description
        $script:Groups += $ADGroup

        foreach ($Group in $ADGroup.MemberOf)
        {
            if ($script:Groups.DistinguishedName -notcontains $Group)
            {
                Get-NestedAdGroups -Identity $Group
            }
        }
    }

    foreach ($Group in (Get-ADUser -Identity $Identity -Properties MemberOf).MemberOf)
    {
        Get-NestedAdGroups -Identity $Group
    }

    return ($script:Groups | Sort-Object -Unique)
}

Get-ADPrincipalGroupMembershipRecurse -Identity $SamAccountName

推荐阅读