在Powershell的ForEach-Object循环中获取当前的哈希键 [英] Getting the current hash key in a ForEach-Object loop in powershell
本文介绍了在Powershell的ForEach-Object循环中获取当前的哈希键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个哈希表:
$myHash = @{
"key1" = @{
"Entry 1" = "one"
"Entry 2" = "two"
}
"key 2" = @{
"Entry 1" = "three"
"Entry 2" = "four"
}
}
我正在遍历以获取对象:
I'm doing a loop through to get the objects:
$myHash.keys | ForEach-Object {
Write-Host $_["Entry 1"]
}
很好,但是我可以用什么来找出我在$myHash
的哪个键中呢? $_.Name
不返回任何内容.我很困惑帮助?
Works fine, but what can I use to figure out which of the keys of $myHash
I'm in? $_.Name
doesn't return anything. I'm stumped. Help?
推荐答案
我喜欢在循环哈希表时使用GetEnumerator()
.它将为您提供对象的属性value
和键/名称的属性key
.试试:
I like to use GetEnumerator()
when looping a hashtable. It will give you a property value
with the object, and a property key
with it's key/name. Try:
$myHash.GetEnumerator() | % {
Write-Host "Current hashtable is: $($_.key)"
Write-Host "Value of Entry 1 is: $($_.value["Entry 1"])"
}
这篇关于在Powershell的ForEach-Object循环中获取当前的哈希键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文