Tagged: array IndexOutOfRangeException
August 12, 2016 at 7:52 pm #50209
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="Why Does This Not Work" Index was outside the bounds of the array. At line:2 char:1 + $data="Why Does This Not Work" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) , IndexOutOfRangeException + FullyQualifiedErrorId : System.IndexOutOfRangeException
August 12, 2016 at 8:39 pm #50232
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 is not valid.
[string]$data=@() $data +="Why Does This Not Work" $data = "It does now"
Edit: typo $data not $date.
- This reply was modified 1 year, 1 month ago by Matt Bloomfield.
August 12, 2016 at 11:12 pm #50245
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 #50272
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 # Remove fred (we could also use $arrayList.Remove('fred') $arrayList.RemoveAt(0) # Bob has moved from index 1 to index 0 Write-Output $arrayList
August 13, 2016 at 3:29 pm #50291
Thanks for explaining this in greater detail. My code now works better.
You must be logged in to reply to this topic.