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

编写PowerShell递归函数为设备组生成完整路径

生成设备组的完整递归路径(PowerShell)

我从API获取了一组PSObjects,示例数据如下:

$testgroups

total device_groups
----- -------------
 1062 {@{id=-2ZPmENMTTSmfNxuGd2Emw; name=Server; description=; created=27/06/2024 10:07:39; modified=27/06/2024 10:07:39; parent_id=T5dNIARCR7OnuzW8IIAsWg...},

$testgroups.device_groups[0..2]

id          : -2ZPmENMTTSmfNxuGd2Emw
name        : Server
description : 
created     : 27/06/2024 10:07:39
modified    : 27/06/2024 10:07:39
parent_id   : T5dNIARCR7OnuzW8IIAsWg

id          : -6XA_2FOSZSw5Bk6HXLewQ
name        : SBC
description : 
created     : 27/06/2024 10:07:40
modified    : 27/06/2024 10:07:40
parent_id   : M8ZBfSjGQtamIAJZpVI7Cw

id          : -GaDYTJbSPaid64tWUDQ_A
name        : RT SCOM_GW
description : group for testing
created     : 27/06/2024 10:07:41
modified    : 27/06/2024 10:07:41
parent_id   : CbuM2_KDQ82BBPlS4lx_Mg

每个对象的parent_id属性指向其父组,根组的该属性为空。需要编写递归函数为每个组生成root\subgroup1\subgroup2格式的完整路径。

解决方案

1. 构建组ID映射哈希表

先把所有组存入哈希表,用ID作为键,递归查找父组时可直接定位,避免重复遍历列表提升性能:

$groupMap = @{}
foreach ($group in $testgroups.device_groups) {
    $groupMap[$group.id] = $group
}

2. 递归函数实现路径生成

编写递归函数,从当前组向上追溯父组直到根组,拼接完整路径:

function Get-GroupFullPath {
    param(
        [Parameter(Mandatory)]
        [PSObject]$Group,
        [Parameter(Mandatory)]
        [hashtable]$GroupMap
    )

    # 根组直接返回名称
    if ([string]::IsNullOrEmpty($Group.parent_id)) {
        return $Group.name
    }

    # 递归获取父组路径,拼接当前组名
    $parentGroup = $GroupMap[$Group.parent_id]
    if ($parentGroup) {
        return (Get-GroupFullPath -Group $parentGroup -GroupMap $GroupMap) + "\$($Group.name)"
    }
    else {
        # 父组不存在时返回当前组名(处理数据异常)
        return $Group.name
    }
}

3. 批量生成路径并添加到组对象

遍历所有组,调用函数生成路径,可将路径作为新属性添加到组对象中:

foreach ($group in $testgroups.device_groups) {
    $fullPath = Get-GroupFullPath -Group $group -GroupMap $groupMap
    $group | Add-Member -NotePropertyName FullPath -NotePropertyValue $fullPath -Force
}

# 查看结果示例
$testgroups.device_groups[0..2] | Select-Object id, name, FullPath

注意事项

  • 若数据存在循环引用(如父组指向子组),递归会触发栈溢出,实际使用可添加参数记录已访问的ID做循环检查
  • 哈希表构建仅需执行一次,后续递归查找为O(1)操作,适合处理大量组数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 08:34:54