15

我有一个哈希表:

$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不返回任何东西。我难住了。帮助?

4

3 回答 3

37

我喜欢GetEnumerator()在循环哈希表时使用。它会给你一个value带有对象的属性,以及一个key带有它的键/名称的属性。尝试:

$myHash.GetEnumerator() | % { 
    Write-Host "Current hashtable is: $($_.key)"
    Write-Host "Value of Entry 1 is: $($_.value["Entry 1"])" 
}
于 2013-02-14T18:02:00.200 回答
5

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

@{
  'foo' = 222
  'bar' = 333
  'baz' = 444
  'qux' = 555
} | % getEnumerator | % {
  $_.key
  $_.value
}
于 2014-10-28T07:16:57.597 回答
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.

于 2015-09-30T08:43:32.557 回答