8

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";

2 Answers 2

12

Christian's answer is the PowerShell way to go and works great for most cases (small to medium size arrays). If your array is large then you may want to consider using ArrayList for performance reasons. That is, every time you use += with an array, PowerShell has to create a new array and copy the old contents into the new array and assign the new array to the variable. That's because .NET arrays are fixed size. Here's how you could do this using an ArrayList:

$list = new-object system.collections.arraylist
$list.Add(("Elem1x", "Elem1y", "Elem1z")) > $null
$list.Add(("Elem2x", "Elem2y")) > $null
$list[0][0]

BTW what the operator += does depends on the type of the object on the left hand side of the operator. If it is a string, then you get string concatenation. If the object is an array, then the right hand side is appended to the array (via create new array/copy).

Sign up to request clarification or add additional context in comments.

1 Comment

I will also add that in my experience, a multi dimensional array is almost always inferior to some other data structure such as suggested here an arraylist of arrays. But I may just be prejudiced against multi dimensional arrays :)
10

Try this way:

$array = @()
$array += ,@("Elem1x", "Elem1y")
$array += ,@("Elem2x", "Elem2y")
$array[0][0]

3 Comments

Can anyone explain what the comma actually does?
The link is dead and I can't find any other references. Anyone has a relevant link nowadays? Found: In expression mode, as a unary operator, the comma creates an array with just one member. Place the comma before the member.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.