I'm trying to save some dynamic string values in an array in my powershell script. As per my knowledge array index starts with 0 till n. Hence I initialize value of index with 0 as $n=0. The array saves value in the 0th location, but in the next loop of foreach when $n=1, it gives an error:
Index was outside the bounds of the array.
My script is like:
$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
}
Output is:
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
This means the array successfully saves the value of $sjt in the array when $n=0 but in the next 2 iterations when $n becomes 1 and 2 respectively it throws an error of 'Index was outside bounds'.
Below workarounds already tried, one by one and in combination:
$arr = @() or $arr = @(1000)
$arr[$n] = @($sjt)
Please assist as where I'm wrong and what needs to be corrected?
$arr += $sjtwhich appends to the array.