在powershell中的ForEach-Object循环中获取当前哈希键

时间:2013-02-14 17:36:30

标签: powershell hashtable

我有一个哈希表:

$myHash = @{ 
   "key1" = @{
       "Entry 1" = "one"
       "Entry 2" = "two"
   }
   "key 2" = @{
       "Entry 1" = "three"
       "Entry 2" = "four"
   }
}

我正在循环获取对象:

$myHash.keys | ForEach-Object {
    Write-Host $_["Entry 1"]
}

工作正常,但我可以用什么来确定$myHash我所处的哪个键? $_.Name不返回任何内容。我很难过。救命?

3 个答案:

答案 0 :(得分:35)

我喜欢在循环哈希表时使用GetEnumerator()。它将为您提供包含对象的属性value,以及包含其键/名称的属性key。尝试:

$myHash.GetEnumerator() | % { 
    Write-Host "Current hashtable is: $($_.key)"
    Write-Host "Value of Entry 1 is: $($_.value["Entry 1"])" 
}

答案 1 :(得分:5)

您也可以在没有变量的情况下执行此操作

@{
  'foo' = 222
  'bar' = 333
  'baz' = 444
  'qux' = 555
} | % getEnumerator | % {
  $_.key
  $_.value
}

答案 2 :(得分:3)

这里是我用来读取ini文件的类似函数。(这个值也是像你这样的字典)。

我转换为哈希的ini文件看起来像这样

[Section1]

key1=value1
key2=value2

[Section2]

key1=value1
key2=value2
key3=value3

从ini哈希表看起来像这样(我传递了转换为哈希的函数):

$Inihash = @{ 
           "Section1" = @{
               "key1" = "value1"
               "key2" = " value2"
           }
           "Section2" = @{
               "key1" = "value1"
               "key2" = "value2"
         "key3" = "value3"
           }
        }

所以从哈希表中这一行将搜索给定部分的所有键/值:

$Inihash.GetEnumerator() |?{$_.Key -eq "Section1"} |% {$_.Value.GetEnumerator() | %{write-host $_.Key "=" $_.Value}} 

? = for search where-object equal my section name. % = you have to do 2 enumeration ! one for all the section and a second for get all the key in the section.