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

PowerShell中如何用递归从嵌套字典按键获取值?

问题解答

先修正示例字典的语法错误

原代码中Audit键的定义缺少等号,不符合PowerShell哈希表的语法规范,修正后代码如下:

$testHashMap = @{
    'feature1' = @{
        'Audit' = @{
          'color' = "white"
          'price' = 3
        }
        'Space'  = 2
        'Usage' = 3
    }
    'feature2' = @{
        'Audit' = @{
          'color' = "black"
          'price' = 3
        }
        'Space'  = 5
        'Usage' = 3
    }
}

1. 直接访问"color"键的值

通过层级索引直接定位目标键:

# 获取feature1下的color值
$testHashMap['feature1']['Audit']['color']
# 输出结果: white

# 获取feature2下的color值
$testHashMap['feature2']['Audit']['color']
# 输出结果: black

2. 递归实现指定键的搜索与返回

编写递归函数遍历哈希表,结合输入交互实现需求:

递归搜索函数

function Find-KeyRecursively {
    param(
        [Parameter(Mandatory)]
        [hashtable]$HashTable,
        [Parameter(Mandatory)]
        [string]$TargetKey,
        [string]$ParentNode = ""
    )

    foreach ($key in $HashTable.Keys) {
        # 记录当前节点的父级路径
        $currentParent = if ($ParentNode) { $ParentNode } else { $key }

        if ($key -eq $TargetKey) {
            # 输出匹配结果,自动过滤中间的Audit层级
            Write-Output "$($TargetKey): $($HashTable[$key]) in $($ParentNode -replace 'Audit > ', '')"
        }
        # 如果当前值仍是哈希表,继续递归遍历
        elseif ($HashTable[$key] -is [hashtable]) {
            $newParent = if ($ParentNode) { "$ParentNode > $key" } else { $key }
            Find-KeyRecursively -HashTable $HashTable[$key] -TargetKey $TargetKey -ParentNode $newParent
        }
    }
}

交互逻辑实现

# 获取用户输入的目标键,自动去除引号
$inputKey = (Read-Host 'Please enter a property') -replace '["'']', ''

# 调用递归函数搜索
Find-KeyRecursively -HashTable $testHashMap -TargetKey $inputKey

运行效果

当输入color时,输出如下:

Please enter a property: "color"
color: white in feature1
color: black in feature2

函数说明

  • 函数会递归遍历哈希表的所有键,若当前键匹配目标键,则输出对应值及其所在的顶级节点(如feature1、feature2)。
  • 遇到嵌套的哈希表时,自动进入下一层级继续遍历,确保不会遗漏深层结构中的目标键。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:32:59