How-to Initialize a Dynamic PowerShell Array

A user asked about creating and assigning values to an array variable in PowerShell over at microsoft.public.windows.powershell. He started off with the following construct and received the errors shown:

PS C:\> $arr = @()
PS C:\> for ( $i = 0 ; $i -lt 3; $i++ ) { $arr[$i] = $i }
Array assignment failed because index ‘0′ was out of range.
At line:1 char:40
+ for ( $i = 0 ; $i -lt 3; $i++ ) { $arr[$ <<<< i] = $i }
Array assignment failed because index ‘1′ was out of range.
At line:1 char:40
+ for ( $i = 0 ; $i -lt 3; $i++ ) { $arr[$ <<<< i] = $i }
Array assignment failed because index ‘2′ was out of range.
At line:1 char:40
+ for ( $i = 0 ; $i -lt 3; $i++ ) { $arr[$ <<<< i] = $i }

Since $arr began life as an empty array, you cannot simply change “nothing” until the individual index items have first been created. You can verify by using $arr.length and the answer will be zero.

To fix this, do the following; PowerShell will automatically create and dynamically expand $arr (”redim” in Visual Basic) to the required size:

PS C:\> for ( $i = 0 ; $i -lt 3; $i++ ) { $arr += @($i) }
PS C:\> $arr.length
3
PS C:\> $arr.gettype().fullname
System.Object[]
PS C:\> $arr
0
1
2
PS C:\> for ( $i = 0 ; $i -lt 3; $i++ ) { $arr[$i] }
0
1
2

Now you can modify the contents of the array accordingly:

PS C:\> $j = 10; for ( $i = 0 ; $i -lt $arr.length; $i++ ) { $arr[$i] = $j*$i }
PS C:\> $arr
0
10
20

By far the simplest way to create an array, assuming you already know the required dimension and type, is demonstrated below:

PS C:\> $arr = 1, 3, 5, 7, 9   #$arr = ,1    #creates an array with a single element
PS C:\> $arr.length
5
PS C:\> $arr.gettype().fullname
System.Object[]
PS C:\> $arr
1
3
5
7
9
PS C:\> for ( $i = 0; $i -lt $arr.length; $i++ ) { $arr[$i] }
1
3
5
7
9

You can also use the New-Object cmdlet to create and initialize the array at the same time. In this case, Int32 objects will be initialized to zero automatically:

PS C:\> $arr = New-Object int[] 3
PS C:\> $arr
0
0
0
PS C:\> for ( $i = 0; $i -lt $arr.length; $i++ ) { $arr[$i] = $i }
PS C:\> $arr
0
1
2

Technorati tags: PowerShell

No Comments »

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.