Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 407
Scott Keck-Warren Avatar asked May 27 '11 20:05

Scott Keck-Warren


People also ask

How do I append an array to another array in PowerShell?

Instead of just using the + operator, we can use the plus and equals signs together to form +=. The += operator is a shortcut that tells PowerShell to add this item to the existing array.

How do I append an array in PowerShell?

To add value to the array, you need to create a new copy of the array and add value to it. To do so, you simply need to use += operator. For example, you have an existing array as given below. To add value “Hello” to the array, we will use += sign.

How do you add to an array of arrays?

To append one array to another, use the push() method on the first array, passing it the values of the second array. The push method is used to add one or more elements to the end of an array. The method changes the contents of the original array. Copied!

Can we append array to array?

1) The push() method adds one or more elements to the end of an array and returns the new length of the array. 3) The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.


1 Answers

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 
like image 153
Roman Kuzmin Avatar answered Sep 28 '22 03:09

Roman Kuzmin