66

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?

2 Answers 2

134

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
Sign up to request clarification or add additional context in comments.

2 Comments

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!
Thank you. Boy does Powershell have some annoying "features".
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

2 Comments

Thanks, the only downside to this is that they are "jagged arrays" and I don't know the upper bound of either the rows or the columns.
I totally edited the wrong comment, please delete my "suggested change" I am really sorry

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.