Function 如何防止递归函数的无限循环

Function 如何防止递归函数的无限循环,function,powershell,recursion,infinite-loop,Function,Powershell,Recursion,Infinite Loop,我正在编写一个自定义函数来获取active directory组成员。之所以写它但不使用Get-ADGroupMember或Get-QADGroupMember,是因为我想跟踪嵌套组中嵌套组之间的关系。标准函数没有它 Function Get-GrpMmbr { param([string]$Identity, [string]$Domain) $Members = Get-ADGroupMember -Identity $Identity -Server $Domain

我正在编写一个自定义函数来获取active directory组成员。之所以写它但不使用Get-ADGroupMember或Get-QADGroupMember,是因为我想跟踪嵌套组中嵌套组之间的关系。标准函数没有它

Function Get-GrpMmbr {
    param([string]$Identity, [string]$Domain)
    $Members = Get-ADGroupMember -Identity $Identity -Server $Domain
    # Pipe through all members. If it is group, then dump info and call itself;
    # Else (not group), dump info.
    $Members | foreach {
        if ($_.objectClass -eq 'group') {
            # Get the groupName and domain name
            $DistinguishedName = $_.distinguishedName
            $Parts = $DistinguishedName -split ","
            foreach ($Part in $parts) {
                if($Part -like "CN=*"){$GroupName = ($Part -split "=")[1]}
                if($Part -like "DC=*"){$DomainName=($Part -split "=")[1];break}
            }
            [PSCustomObject]@{
                'UserName' = $_.name
                'UserID' = $_.SamAccountName
                'GroupName' = $Identity ## show the group from the direct parent group
                'Type'= "Group"
            } # end of new object
            # recursion happens here
            Get-EFSGrpMmbr -Identity $GroupName -Domain $DomainName
        } else {
            [PSCustomObject]@{
                'UserName' = $_.name
                'UserID' = $_.SamAccountName
                'GroupName' = $Identity
                'Type' = "User"
            } # end of new object
        } # end of Else
    } # end of foreach loop
} # end of function
问题:它进入无限循环,出现以下情况:

Get-GrpMmbr -Identity 'GroupA' -Domain 'NW'
条件是:A组是B组的成员;B组是C组的成员;GroupC是GroupA的成员

那么,如何停止无限循环呢

Function Get-GrpMmbr {
    param([string]$Identity, [string]$Domain, [array]$Path = @())
    If ($Path -contains $Identity) {Return}
    ...
    Get-GrpMmbr $GroupName $DomainName ($Path + $Identity)
    ...
}
如果要显示无限循环:

Function Get-GrpMmbr {
    param([string]$Identity, [string]$Domain, [array]$Path = @())
    $i = [array]::indexof($Path, $Identity)     #In case of a sAMAccountName you might want to ignore the case
    If ($i -ge 0) {
        Write-Host "Inifitive loop:" $Path[$i..999]
        Return
    }
    ...
    Get-GrpMmbr $GroupName $DomainName ($Path + $Identity)
    ...
}

对获取EFSGrpMmbr的调用感到困惑。这是另一个函数,还是Get-GrpMember的别名?当然,有点让人困惑。它可以变成你喜欢的任何东西。这不是我的问题。[System.Collections.ArrayList]$Global:CompletedGroups=@。在处理组名时向其添加组名,在进行递归调用之前检查$GroupName-是否在其中。报告此类循环关系也是一个好主意,因为它们确实不是一个好主意。@TessellingHeckler我认为将父组列表作为参数传递可能比修改全局变量更干净。