提问人:Ichigo Kurosaki 提问时间:5/28/2023 最后编辑:mklement0Ichigo Kurosaki 更新时间:5/29/2023 访问量:288
从 Powershell 中的密钥(嵌套字典中)获取值
Get Value from Key (in Nested Dictionary) in Powershell
问:
我的示例词典
$testHashMap = @{
'feature1' = @{
'Audit'@{
'color' = "white"
'price' = 3
}
'Space' = 2
'Usage' = 3
}
'feature2' = @{
'Audit'@{
'color' = "black"
'price' = 3
}
'Space' = 5
'Usage' = 3
}
}
- 如何直接访问“color”键的值?
- 当我提示一个键时,它将是与搜索相关的键并返回其值
预期输出:
Please enter a property: "color"
Color: white in feature1
Color: black in feature2
我想用递归来做,我怎样才能达到这个目的?
答:
0赞
mklement0
5/29/2023
#1
此答案中的自定义函数可以处理任意对象图作为输入,包括嵌套的哈希表(字典),如您的问题所示。Get-LeafProperty
它将叶属性/字典条目报告为名称-路径/值对;例如,对于您的第一个条目,它返回以下自定义对象(此处表示为文本):color
[pscustomobject] @{ NamePath = 'feature1.Audit.color'; Value = 'white' }
因此,可以将此函数与 Where-Object 和
ForEach-Object
结合使用,以按感兴趣的叶键筛选输出:
$keyName = 'color'
# The key of the leaf entries of interest.
$keyName = 'color'
@{ # sample input hashtable from you question; streamlined and syntax-corrected
feature1 = @{
Audit = @{
color = 'white'
price = 3
}
Space = 2
Usage = 3
}
feature2 = @{
Audit = @{
color = 'black'
price = 3
}
Space = 5
Usage = 3
}
} |
Get-LeafProperty |
Where-Object { ($_.NamePath -split '\.')[-1] -eq $keyName } |
ForEach-Object {
"${keyName}: $($_.Value) in $(($_.NamePath -split '\.')[0])"
}
输出:
color: white in feature1
color: black in feature2
评论
GetEnumerator()