Getting the current hash key in a ForEach-Object loop in powershell

前端 未结 3 1274
生来不讨喜
生来不讨喜 2021-02-07 10:37

I\'ve got a hash table:

$myHash = @{ 
   \"key1\" = @{
       \"Entry 1\" = \"one\"
       \"Entry 2\" = \"two\"
   }
            


        
3条回答
  •  离开以前
    2021-02-07 11:03

    here a similare function i used to read ini file.(the value are also a dictionary like yours).

    ini file that i transform into hash look like this

    [Section1]
    
    key1=value1
    key2=value2
    
    [Section2]
    
    key1=value1
    key2=value2
    key3=value3
    

    From the ini the hashtable look like this (i passed the fonction that do the transformation in to hash):

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

    so from the hash table this line will search all the key/value for a given section:

    $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.

提交回复
热议问题