62

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

127

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
2
  • 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, 2012 at 13:20
  • 14
    Thank you. Boy does Powershell have some annoying "features".
    – David
    Apr 3, 2013 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
2
  • 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. May 31, 2011 at 12:09
  • I totally edited the wrong comment, please delete my "suggested change" I am really sorry Aug 14, 2018 at 13:06

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.