首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归函数在写入主机和在数组中保存时有不同的结果。

递归函数在写入主机和在数组中保存时有不同的结果。
EN

Stack Overflow用户
提问于 2018-04-06 08:15:31
回答 1查看 111关注 0票数 0

我对递归函数有一个问题,该函数递归地获取组的所有父组。

我的功能是这样的

代码语言:javascript
复制
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
}

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

在这里,我如何使用我的功能和测试

代码语言:javascript
复制
$groupsParent = @()
$groupsParent = Get-ADPrincipalGroupMembershipRecursive -groupName "g-assistants" -list $groupsParent
write-host "Length" $groupsParent.Length
$groupsParent

我得到以下输出

代码语言:javascript
复制
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-assistantsG-eGR G-ePA G-eRPP G-ePO HP-Designjet-Z6800ps G-scan313中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-06 10:31:46

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

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

我对你的脚本做了这些修改:

代码语言:javascript
复制
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

希望它有帮助:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49688350

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档