使用数组时 PowerShell 出错

Error in PowerShell while using arrays

当我尝试为数组的特定索引赋值时,它显示错误。 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

`

那是因为您必须先初始化 数组。如果你知道数组的大小,你可以这样做:

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

考虑使用 哈希表:

$names = @{}
$names[1] = "abc"