You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PowerShell数组转换为层级结构树并递归遍历子节点

PowerShell递归遍历层级数组并生成缩进式列表

我有一个包含Id、Name、ParentRoleId字段的PowerShell数组,想要把它转换成层级结构展示——没有ParentRoleId的项作为根节点,最终输出缩进式的层级列表。我已经写了GetChildren函数用来获取节点的子节点,但不知道怎么递归遍历到最底层,求完整的递归实现方法。

数组数据示例

Id                  Name                  ParentRoleId
00E6T000002G5sXUAS  APAC AE, Commercial  00E6T000002G3skUAC
...(其余数据略)

现有代码

GetChildren函数

function GetChildren ($param)
{
    Foreach ($x in $param) {
        ($hierarchyarray | where {$_.parentroleid -EQ $x}).id
    }
}

根节点定义

$root = $hierarchyarray | where {$_.parentroleid -EQ $null}

递归遍历实现方案

可以编写一个递归函数,直接处理节点并输出带缩进的层级结构,替代原有的GetChildren函数完成全层级遍历:

function Show-Hierarchy {
    param(
        [Parameter(Mandatory=$true)]
        $Nodes,
        [int]$IndentLevel = 0
    )

    # 根据缩进级别生成空格
    $indent = '    ' * $IndentLevel
    foreach ($node in $Nodes) {
        # 输出当前节点名称,带对应缩进
        Write-Host "$indent$($node.Name)"
        
        # 查找当前节点的所有子节点
        $children = $hierarchyarray | Where-Object { $_.ParentRoleId -eq $node.Id }
        
        # 存在子节点则递归调用,缩进级别加1
        if ($children) {
            Show-Hierarchy -Nodes $children -IndentLevel ($IndentLevel + 1)
        }
    }
}

# 启动遍历,从根节点集合开始
Show-Hierarchy -Nodes $root

代码说明

  • 函数核心逻辑是处理当前节点→查找子节点→递归处理子节点的循环,直到遍历完所有层级
  • IndentLevel参数控制缩进深度,每深入一层,缩进增加4个空格(可根据需求调整' '的长度)
  • 直接输出节点名称,也可以根据需求修改输出内容(比如同时输出Id)

内容的提问来源于stack exchange,提问作者nikfinity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:25:18