0

While I am trying to assign a value to the specific index of an array it is showing the Errors. PS /home/mifi> $names = @()

PS /home/mifi> $names[1]="abc" Index was outside the bounds of the array. At line:1 char:1 + $names[1]="abc" + ~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], IndexOutOfRangeException + FullyQualifiedErrorId : System.IndexOutOfRangeException

pwsh -v
PowerShell v6.0.2

`

3
  • 1
    Show $names.Length. Commented Jun 7, 2018 at 6:34
  • Please show enough code to re-create. Commented Jun 7, 2018 at 6:39
  • Do you try the same with clean session? Show $names.GetType().FullName. Also, please, edit tags to match content of your question. Commented Jun 7, 2018 at 6:57

1 Answer 1

1

Thats because you have to initialize the array first. If you know the size of the array you can do it like this:

$arraySize = 10
$names= 1..$arraySize | foreach { $null }

Consider using a hashtable:

$names = @{}
$names[1] = "abc"
Sign up to request clarification or add additional context in comments.

5 Comments

Your $names will not be array, when $arraySize is 1. Also with $arraySize equals to 0 it will create array with 2 elements.
@PetSerAl Good point, Keshav should keep that in mind. Depending on his requirements a hashtable would be preferable.
@Martin Brandl, It is still showing the error by using your above code and plus I have mentioned the version of the Powershell.
@MartinBrandl actually I was using () instead of { } curly braises as it was mention in the older book to use ( ).
We need to see your code but using @() will give you an array whereas @{} creates a hashtable. That are two different things

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.