How do I populate an array of unknown length in Powershell?

Try this way:

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

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).

Tags:

Powershell