Louis J.
Louis J.

Reputation: 49

Iterating multidimensional hashtables in powershell

I have to iterate trought a multidimensional hashtable like:

$ou=@{
      class = @{
              value1 = @{
                       1= ""
                       }
              value2 = ""
              value3 = ""
              }
      }

All I need is a way to access every key of the hashtable (values1, value2, ...). I already tried foreach and for loops but without success. At first I used a foreach loop to iterarte trought the first hashtable:

foreach ($key in $a.keys){
    write-host $key.keys
}

But I struggle adding a second loop. Do I have to iterate the keys again? And why does $key.keys give me all the keys back and not one after the other?

Upvotes: 3

Views: 3825

Answers (1)

Bruce Payette
Bruce Payette

Reputation: 2629

This

function keys ($h) { foreach ($k in $h.keys) { $k ; keys $h[$k] }}

will recurse through all the keys. Note that it recurses on the value of the hashtable element not the key. So in your comment example, you probably wanted to iterate over $a[$key].key not $key.keysin in the second-level loop.

Upvotes: 5

Related Questions