60

I'm trying to build up a multi-dimensional array in PowerShell programmatically using CSV files located on disk. I have been importing the array into a temporary variable and then appending the array to the array. Instead of an array of arrays I get a single array with the total number of rows. I worked it out with smaller arrays and found the following:

$array1 = "11","12","13"
$array2 = "21","22","23"
$array3 = "31","32","33"

$arrayAll = $array1, $array2, $array3
$arrayAll.Count # returns 3

$arrayAll = @();
$arrayAll += $array1
$arrayAll += $array2
$arrayAll += $array3

$arrayAll.count # returns 9

The first method for building the array works but I need to be able to use the second method. How do I fix this?

Scott Keck-Warren
  • 1,894
  • 3
  • 18
  • 33

2 Answers2

124

It's a common gotcha, arrays (and other collections) may get unrolled "unexpectedly". Use the comma operator (it makes/enforces an array with a single item and avoids unrolling):

$array1 = "11","12","13"
$array2 = "21","22","23"
$array3 = "31","32","33"

$arrayAll = $array1, $array2, $array3
$arrayAll.Count # returns 3

$arrayAll = @()
$arrayAll += , $array1
$arrayAll += , $array2
$arrayAll += , $array3

$arrayAll.count # returns 3

$arrayAll[1] # gets "21","22","23", i.e. $array2
Roman Kuzmin
  • 40,627
  • 11
  • 95
  • 117
  • 1
    I love stackoverflow... i've been looking for how to do this the whole day, just to find the weird comma-solution. Just for the reference, i was doing this with strings, without the comma's. When you ask for $arrayAll[0][0] then, for example, you get the first character of the first string. Weird... but this solves it! – Wouter Oct 17 '12 at 13:20
  • 14
    Thank you. Boy does Powershell have some annoying "features". – David Apr 03 '13 at 14:49
6

Not sure I undestand what you are looking for, but it can help.

PS> $arrayAll = New-Object int[][] (3,3)
PS> $arrayAll[0] = $array1
PS> $arrayAll[1] = $array2
PS> $arrayAll[2] = $array3

PS> $arrayAll.Count
3

PS> $arrayAll[1][2]
23

It's a way to code an array of array.

Here is a way to code an array of two dimensions

PS> $arrayAll = New-Object 'int[,]' (3,3)
PS> $arrayAll[2,0] = 12
JPBlanc
  • 70,406
  • 17
  • 130
  • 175