Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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

like image 288
Nilzor Avatar asked Oct 12 '12 14:10

Nilzor


People also ask

How do I get the length of an array in PowerShell?

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.

How do I add values to an array in PowerShell?

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.

How do you create an array of strings in PowerShell?

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.

What does @() mean in PowerShell?

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.


1 Answers

Try this way:

$array = @()
$array += ,@("Elem1x", "Elem1y")
$array += ,@("Elem2x", "Elem2y")
$array[0][0]
like image 89
CB. Avatar answered Nov 01 '22 11:11

CB.