当写主机并保存在数组中时,递归函数有不同的结果

时间:2018-04-06 08:15:32

标签: powershell

我有一个递归函数的问题,它以递归方式获取组的所有父组。

我的功能看起来像这样

function Get-ADPrincipalGroupMembershipRecursive ($groupName,$list)
{
  $groupsMembership = Get-ADPrincipalGroupMembership $groupName

  foreach ($groupMembership in $groupsMembership)
  {
    write-host $groupMembership.name
    $list += $groupMembership.name
    Get-ADPrincipalGroupMembershipRecursive -groupName 
    $groupMembership -list $list
  }

  return $list
}

当我调用我的函数时,我希望在控制台上获得相同的输出,当我回显列表时。但是写主机写的东西是正确的,但在列表中我得到重复的条目。

这是我如何使用我的功能和测试

$groupsParent = @()
$groupsParent = Get-ADPrincipalGroupMembershipRecursive -groupName "g-assistants" -list $groupsParent
write-host "Length" $groupsParent.Length
$groupsParent

我得到以下输出

G-eGR
G-ePA
G-eRPP
G-ePO
HP-Designjet-Z6800ps
G-scan313
Length 27
G-eGR
G-eGR
G-ePA
G-eGR
G-ePA
G-eRPP
G-eGR
G-ePA
G-eRPP
G-ePO    
G-eGR
G-ePA
G-eRPP
G-ePO
HP-Designjet-Z6800ps
G-eGR
G-ePA
G-eRPP
G-ePO
HP-Designjet-Z6800ps
G-scan313
G-eGR
G-ePA
G-eRPP
G-ePO
HP-Designjet-Z6800ps
G-scan313

使用此示例组,组g-assistants位于G-eGR G-ePA G-eRPP G-ePO HP-Designjet-Z6800ps G-scan313

1 个答案:

答案 0 :(得分:0)

您在输出中收到重复的条目,因为您在每个调用中传递$ list;在每次迭代中,您都会更新并发送它。

您应该从递归函数输出有关其处理的组的信息,并在调用函数中输出该输出并将其添加到列表中。

我对您的脚本进行了这些更改:

function Get-ADPrincipalGroupMembershipRecursive ($groupName)
{
  # Empty list. The current function call knows nothing about who called it
  $list = @()

  # Add the current group to the list
  $list += $groupName

  Write-Host $groupName 

  $groupsMembership = Get-ADPrincipalGroupMembership $groupName

  foreach ($groupMembership in $groupsMembership.Name)
  {
    # Add all child groups to the list
    $list += Get-ADPrincipalGroupMembershipRecursive -groupName $groupMembership
  }

  # Return the current group and all its children
  return  $list
}

$groupsParent = Get-ADPrincipalGroupMembershipRecursive -groupName $groupName
write-host "Length" $groupsParent.Length
$groupsParent

希望有所帮助:)