PowerShell array initialization PowerShell array initialization arrays arrays

PowerShell 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> $aFalseFalseFalseFalseFalse

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)> $aFalseFalseFalseFalseFalse

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

> $a = (1..5)   > $a12345

Hope this was somewhat helpful!


Yet another alternative:

for ($i = 0; $i -lt 5; $i++) {   $arr += @($false) }

This one works if $arr isn't defined yet.

NOTE - there are better (and more performant) ways to do this... see https://stackoverflow.com/a/234060/4570 below as an example.