3

I want to create a multidimensional array in powershell like this:

$array[0] = "colours"
$array[0][0] = "red"
$array[0][1] = "blue"
$array[1] = "animals"
$array[1][0] = "cat"
$array[1][0] = "dog"

Here's what i tried:

$array = @()
$array += "colours"
$array += "animals"

$array[0] # outputs "colours"
$array[1] # outputs "animals"

$array[0] = @()
$array[1] = @()

$array[0] += "red"
$array[0] += "blue"
$array[1] += "cat"
$array[1] += "dog"

$array[0] # outputs "red", "blue" - i expected "colours" here
$array[0][0] # outputs "red"

I appreciate any hints.

Thanks in advance

fuser60596
  • 877
  • 1
  • 11
  • 24

2 Answers2

7

It looks like you'd be better off with a [hashtable] (also called an associative array):

$hash = @{
    colours = @('red','blue')
    animals = @('cat','dog')
}

$hash.Keys  # show all the keys

$hash['colours']  # show all the colours
$hash.colours   # same thing

$hash['colours'][0]  # red

$hash['foods'] = @('cheese','biscuits')  # new one
$hash.clothes = @('pants','shirts')  #another way

$hash.clothes += 'socks'
briantist
  • 42,842
  • 6
  • 72
  • 111
4

You can't do what you're trying to do with a nested array:

$array = @()
$array += "colours"

makes $array[0] contain string colours, but you then replace that value by assigning an empty array to $array[0]: $array[0] = @(). With that, your colours value is gone.

You later fill that array with strings red and blue, so that $array[0] ends up containing a 2-element string array, @( 'red', 'blue' ).


One option is to use a hashtable as the type of the elements of the top-level array:

$array = @()
$array += @{ name = 'colours'; values = @() }

$array[0].values += 'red'
$array[0].values += 'blue'

$array[0].name   # -> 'colours'
$array[0].values # -> @( 'red', 'blue' )
mklement0
  • 312,089
  • 56
  • 508
  • 622