递归获取 user/group 的所有组

Get all Groups of a user/group recursively

我有一些代码可以获取用户的组并将它们写到 Arraylist 中,但是它只会找到用户直接所在的组。它不会找到比 1 级更深的组。

例如:用户是群组 1 的成员,群组 1 是群组 2 的成员,等等。 我只会找到第 1 组。第 2 组不会写到我的 ArrayList 中。

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

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

有人可以帮我吗?谢谢

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

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