我試圖在PowerShell腳本中的數組中保存一些動態字符串值。根據我的知識,數組索引從0開始,直到n。因此,我初始化索引值爲0 $n=0
。數組中的第0個位置保存價值,但在的foreach時$n=1
的下一個循環,它給出了一個錯誤:將字符串值保存到數組中時Powershell錯誤
Index was outside the bounds of the array.
我的腳本是這樣的:
$arr = @(100)
$n=0
$sj=Select-String -Path C:\Script\main.dev.json -pattern '".*":' -Allmatches
foreach($sjt in $sj.Line)
{
Write-host "n=" $n
Write-Output $sjt
$arr[$n] = $sjt
$s=Select-String -Path C:\Script\$js -pattern '.*"' -Allmatches
$n=$n+1
}
輸出是:
n= 0
"Share": "DC1NAS0DEV",
n= 1
"Volume": "devVol",
Index was outside the bounds of the array.
At C:\Script\fstest.ps1:30 char:2
+ $arr[$n] = $sjt
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], IndexOutO
on
+ FullyQualifiedErrorId : System.IndexOutOfRangeException
n= 2
"DbServer": "10.10.10.dev"
Index was outside the bounds of the array.
At C:\Script\fstest.ps1:30 char:2
+ $arr[$n] = $sjt
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], IndexOutO
on
+ FullyQualifiedErrorId : System.IndexOutOfRangeException
這意味着當數組$n=0
時,數組成功地將$sjt
的值保存在數組中,但在接下來的2次迭代中,當$ n變爲1和2時,數組有意思的是它會拋出'索引超出範圍'的錯誤。
以下解決方法已經嘗試過,一招一式的組合:
$arr = @() or $arr = @(1000)
$arr[$n] = @($sjt)
請幫助,那是我錯了,哪些需要修正?
刪除引用該數組的索引,並執行附加到該數組的$ arr + = $ sjt'。 – t0mm13b
完美。 $ arr + = $ sjt工作。 -Thanks and Regards –