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
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.
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.
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.
Here's two more ways, both very concise.
$arr1 = @(0) * 20 $arr2 = ,0 * 20
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!
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