I want to create an array of arrays in PowerShell.
$x = @( @(1,2,3), @(4,5,6) )
It works fine. However, sometimes I have only one array in the array list. In that situation, PowerShell ignores one of the lists:
$x = @( @(1,2,3) ) $x[0][0] # Should return 1 Unable to index into an object of type System.Int32. At line:1 char:7 + $a[0][ <<<< 0] + CategoryInfo : InvalidOperation: (0:Int32) [], RuntimeException + FullyQualifiedErrorId : CannotIndex
How do I create an array of arrays, guaranteed it remains as a two-dimensional array even if the array has only one array item in it?
Use += to Add Objects to an Array of Objects in PowerShell The Plus Equals += is used to add items to an array. Every time you use it, it duplicates and creates a new array. You can use the += to add objects to an array of objects in PowerShell.
You can use the += operator to add an element to an array. The following example shows how to add an element to the $a array. When you use the += operator, PowerShell actually creates a new array with the values of the original array and the added value.
Syntax of PowerShell Multidimensional Array So for example, if we need an array of numbers than we can define int32, in the same way, if we need an array with string then we can define with string. $array = @( @(“data2”), @(“data3”), @(“data4”) …….)
Adding a comma force to create an array:
$x = @( ,@(1,2,3) )
Simple way:
$x = ,(1,2,3)
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