Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 872
Louis J. Avatar asked Mar 24 '26 06:03

Louis J.


1 Answers

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.

like image 136
Bruce Payette Avatar answered Mar 26 '26 04:03

Bruce Payette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!