Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell array initialization

What's the best way to initialize an array in PowerShell?

For example, the code

$array = @() for($i=0; $i -lt 5;$i++) {     $array[$i] = $FALSE } 

generates the error

Array assignment failed because index '0' was out of range. At H:\Software\PowerShell\TestArray.ps1:4 char:10 +         $array[$ <<<< i] = $FALSE 
like image 753
Eric Ness Avatar asked Oct 22 '08 16:10

Eric Ness


People also ask

How do you initialize in array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

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 declare an array and initialise it?

Initializing an array In order to store values in the array, we must initialize it first, the syntax of which is as follows: datatype [ ] arrayName = new datatype [size]; There are a few different ways to initialize an array. Look at the following examples to get a better idea about array initialization.


2 Answers

Here's two more ways, both very concise.

$arr1 = @(0) * 20 $arr2 = ,0 * 20 
like image 101
halr9000 Avatar answered Oct 13 '22 04:10

halr9000


You can also rely on the default value of the constructor if you wish to create a typed array:

> $a = new-object bool[] 5 > $a False False False False False 

The default value of a bool is apparently false so this works in your case. Likewise if you create a typed int[] array, you'll get the default value of 0.

Another cool way that I use to initialze arrays is with the following shorthand:

> $a = ($false, $false, $false, $false, $false) > $a False False False False False 

Or if you can you want to initialize a range, I've sometimes found this useful:

 > $a = (1..5)    > $a 1 2 3 4 5 

Hope this was somewhat helpful!

like image 27
Scott Saad Avatar answered Oct 13 '22 04:10

Scott Saad