views:

4568

answers:

7

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
+3  A: 

The solution I found was to use the New-Object cmdlet to initialize an array of the proper size.

$array = new-object object[] 5 
for($i=0; $i -lt $array.Length;$i++)
{
 $array[$i] = $FALSE
}
Eric Ness
mark yourself as the answer por favor
Peter Seale
+2  A: 

If I don't know the size up front, I use an arraylist instead of an array.

$al = New-Object System.Collections.ArayList
for($i=0; $i -lt 5; $i++)
{
    $al.Add($i)
}
EBGreen
+7  A: 

Yet another alternative:

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

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

Some good posts on PowerShell and arrays:

http://www.leedesmond.com/weblog/?p=183
http://get-powershell.com/2008/02/07/powershell-function-new-array/

David Mohundro
+3  A: 

This works too

$array = @()
for($i=0; $i -lt 5; $i++)
{
    $a += $i
}
EBGreen
+3  A: 

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!

Scott Saad
+3  A: 
$array = 1..5 | foreach { $false }
Peter Seale
I like this, I dropped a % in place of the foreach and it gives it a really tight initialization.
Chris Sutton
+8  A: 

Here's two more ways, both very concise.

$arr1 = @(0) * 20
$arr2 = ,0 * 20
halr9000
Very nice, I was trying to figure this out this morning and I think you gave the most concise way to initialize an array.
Chris Sutton
Thanks. There's more info here on my blog where this topic came up Sept 2007. http://halr9000.com/article/430
halr9000
this is rad. A+
spoon16