Author Posts

August 12, 2016 at 7:52 pm

ps version 5.1.14393.0

I'm struggling to understand why the snippet below fails.
1. I've strongly typed the array
2. I've initialized it (yes, to null).
3. Then I proceed to load the first element with a string.

But what happens is that powershell sees this as a Character Array() and not as a string.

Why doesn't powershell make this assignment?
What is the correct code to make this work?

[string[]]$data=@()
$data[0]="Why Does This Not Work"

Index was outside the bounds of the array.
At line:2 char:1
+ $data[0]="Why Does This Not Work"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], IndexOutOfRangeException
    + FullyQualifiedErrorId : System.IndexOutOfRangeException

August 12, 2016 at 8:39 pm

Your array is empty so the only index that exists is -1.
You can't access index 0 until you add something to the array so $data[0] is not valid.

[string[]]$data=@()
$data +="Why Does This Not Work"
$data[0] = "It does now"

Edit: typo $data not $date.

August 12, 2016 at 11:12 pm

Thanx. I see that using the += assignment operator worked perfectly.

What other ways could I expand my array dynamically other than using the += assignment operator?

Is using the += assignment operator the only way to add elements on the fly?

August 13, 2016 at 10:15 am

PowerShell doesn't actually expand arrays dynamically. When you add an object to the array, it's contents are copied to a new array object with the addition and the original array object is destroyed. This is inefficient and slow when you're working with large arrays. Also, you can't remove objects from an array.

For dynamic and large arrays folks normally opt for Systems.Collections.ArrayList

# Create the arrayList collection object
$arrayList = New-Object System.Collections.ArrayList
# The first object we add will be at index 0
$arrayList.Add('fred')
# The second object we add will be at index 1
$arrayList.Add('bob')
# Fred is at position 0
Write-Output $arrayList[0]
# Remove fred (we could also use $arrayList.Remove('fred')
$arrayList.RemoveAt(0)
# Bob has moved from index 1 to index 0
Write-Output $arrayList[0]

August 13, 2016 at 3:29 pm

Thanks for explaining this in greater detail. My code now works better.