How do you work with dynamic-length arrays (ArrayLists / Lists) in Powershell? I basically want a 2D-array where the length of the outermost index is unknown.
I tried initializing an array with $array = @()
, but would get index out of range exceptions when addressing anything in this. Then I tried using the += operand, as I read in an article, but that would result in string concatenation and not element addition.
Example:
$array = @()
$array += @("Elem1x", "Elem1y")
$array += @("Elem2x", "Elem2y")
Echo $array[0][0]
Output: "E" instead of "Elem1x";
Count or Length or LongLength To determine how many items are in an array, use the Length property or its Count alias. Longlength is useful if the array contains more than 2,147,483,647 elements.
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.
Create an Array of Strings in PowerShell Using the @() Method. Another method to create an array of strings in PowerShell is the “@()” method. Define your array name, and store its sting values within the () brackets after the “@” symbol.
Array subexpression operator @( )Returns the result of one or more statements as an array. The result is always an array of 0 or more objects. PowerShell Copy.
Try this way:
$array = @()
$array += ,@("Elem1x", "Elem1y")
$array += ,@("Elem2x", "Elem2y")
$array[0][0]
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