2017-06-12 63 views
2

我試圖在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) 

請幫助,那是我錯了,哪些需要修正?

+0

刪除引用該數組的索引,並執行附加到該數組的$ arr + = $ sjt'。 – t0mm13b

+0

完美。 $ arr + = $ sjt工作。 -Thanks and Regards –

回答

3

@(100)是一個只有一個元素的數組,100。不是100個元素的數組。你可以使用$array = 0..99來創建一個包含100個元素的數組。但我不認爲這就是你想要的。

您可以創建一個空數組,然後向其中添加元素。

$arr = @() 
foreach ($sjt in $sj.Line) { 
    $arr += $sjt 
    $s = Select-String -Path C:\Script\$js -pattern '.*"' -Allmatches 
    $n = $n+1 
} 

或者(稍微高效),您可以設置變量等於您的循環輸出並輸出該值。

$arr = foreach ($sjt in $sj.Line) { 
    $sjt 
    $s = Select-String -Path C:\Script\$js -pattern '.*"' -Allmatches 
    $n = $n+1 
} 
+0

通過簡單地使用$ arr + = $ sjt解決了問題,該解決方案也由上面的t0mm13b提出。但我很想知道爲什麼$ arr [$ n] = $ sjt不會通過增加'n'evrytime的值來工作。這適用於C++及其邏輯。你知道原因嗎? –

+0

@BriteRoy它會工作,如果你的數組有足夠的元素。這是我在答案開始時確定的。如果您知道數組元素的確切數目,則此方法效果最佳,否則正如您在嘗試索引數組時所注意到的,並且該元素不存在,則會收到錯誤,或者最終會在數組中出現無意義的額外元素。 '+ ='方法創建一個新數組並複製舊值和新值,所以它不是超高效的。第三種方法沒有這些缺點。 – BenH

+0

遲到回覆,但感謝@BenH的解釋。 –