Search code examples
arrayspowershelldictionaryhashtable

Powershell - How to iterate over array that is a value in a dictionary


I have a particular case in Powershell that I didn't think would be a problem but apparently, it is.

I have data that I read from a file in the following structure:

$dict=[ordered]@{
   "key1"=@(
             "value1",
             "value2",
             "value3"          
           );
   "key2"=@(
             "value1",
             "value2"         
           );
}

... and so on. A dictionary with keys that have arrays of strings as their value. When I try to iterate through the array and make another string with each of the array items, the array of strings gets "flattened out" into a single string. For example:

foreach($Key in $dictionary){

    foreach($item in $Key.Values){
        $newString="New string with $item"
        $newString
        }   
}

The output (just for the first key) is

"New string with value1 value2 value3"

Instead of what I would expect

"New string with value1"
"New string with value2"
"New string with value3"

And the weirdest part is that when I just print out the values without making the new string, it prints every item individually as it should.

I really don't understand this behavior from what should be a very elementary iteration. Can anyone explain to me why this is happening, and what the proper way to do this is?


Solution

  • You need to enumerate the root array:

    foreach($Key in $dict.GetEnumerator()){
        foreach($item in $Key.Value){
            $newString="New string with $item"
            $newString
        }   
    }
    

    Or use its actual keys:

    foreach($Key in $dict.Keys){
        foreach($item in $Dict[$Key].Value){
            $newString="New string with $item"
            $newString
        }   
    }