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

`

Keshav Maheshwari
  • 85
  • 1
  • 2
  • 12

1 Answers1

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"
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172