Search code examples
arrayspowershellmultidimensional-arrayjagged-arrays

How can i declare a multi dimensional array in Powershell?


I have an array as follows:

 $apps = @('app1', 'app1a', 'app1b', 'app2', 'app2a', 'app2b')

Now app1 , app1a and app1b are all related, so I want them in one item in the array and able to access:

I have tried:

$test = @{test1 = (app,app1a,app1b);test2 = (app2,app2a,app2b);}

 foreach($item in $test.GetEnumerator()){
  $key = $item.key
  $value = $item.value
  Write-Output $key $value
 }

But i want to access each item in the array and then each item in that . How can i do that ?


Solution

  • To answer the question implied by your post's title: [string[,]]::new(3,2) creates a true two-dimensional array in PowerShell that would fit your data, but such arrays are rarely needed in PowerShell.

    To work with arrays only (@(...)) - as opposed to hashtables (@{ ... }) - use a jagged array:

    # Note: You could enclose the entire RHS in @(...) too, but it isn't necessary.
    #       For the same reason, the following is sufficient:
    #          $apps = ('app1', 'app1a', 'app1b'), ('app2', 'app2a', 'app2b')
    $apps = @('app1', 'app1a', 'app1b'), @('app2', 'app2a', 'app2b')
    

    That is, $apps is then an array of arrays, specifically a two-element array whose elements are themselves arrays.

    Then, $apps[0] yields @('app1' 'app1a', 'app1b'), and $apps[1] yields @('app2', 'app2a', 'app2b'), and you can use nested indexing to access individual elements in either; e.g. $apps[0][1] yields 'app1a'

    To enumerate the elements in each "dimension" using a foreach statement, use something like:

    # Outputs '[app1]', '[app1a]', and '[app1b]', each on its own line.
    foreach ($el in $apps[0]) { "[$el]" }
    

    If you do want to use hashtables:

    $apps = @{
      test1 = @('app1', 'app1a', 'app1b')
      test2 = @('app2', 'app2a', 'app2b')
    }
    

    Then you can use, e.g. $apps['test1'][1] as well as $apps.test1[1] to retrieve 'app1a'

    To enumerate the elements associated with a given key using foreach, use something like:

    # Outputs '[app1]', '[app1a]', and '[app1b]', each on its own line.
    foreach ($el in $apps.test1) { "[$el]" }