Keshav Maheshwari
Keshav Maheshwari

Reputation: 95

Error in PowerShell while using arrays

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

`

Upvotes: 0

Views: 1018

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 59001

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"

Upvotes: 1

Related Questions