Append an Array to an Array of Arrays in PowerShell

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?


Solution 1:

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

Solution 2:

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