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?
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.
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.
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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With