Strong Typed String Array Fails

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?

$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

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.

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

Edit: typo $data not $date.

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?

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
# The second object we add will be at index 1
# Fred is at position 0
Write-Output $arrayList[0]
# Remove fred (we could also use $arrayList.Remove('fred')
# Bob has moved from index 1 to index 0
Write-Output $arrayList[0]

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