windowsshellpowershellpowershell-2.0windows-hello

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

`


Solution

  • 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"