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
相关产品推荐
相关产品推荐

