简体   繁体   中英

Index was outside the bounds of the array powershell

I want multiple data fetching from excel sheet. I am getting error is Index was outside the bounds of the array.

$Data = Read-Host "Enter the count of Datastore"
$ds = "-sm-"
$Range1 = $Worksheetx1.Range("B1","B1048570")
$Search1 = $Range1.find($ds)
$r = $Search1.row

for ($i=1; $i -le $Data; $i++)
    {
    $Datastore = @()
    $Datastore[$i] = $Worksheetx1.Cells.Item($r, 2).Value2
    $r = $r+1
    }

$Total_Datastore = $Datastore1 + $Datastore2 + $Datastore3 + $Datastore4

$Total_Datastore

The problem resides in this code:

for ($i=1; $i -le $Data; $i++)
{
    $Datastore = @()
    $Datastore[$i] = $Worksheetx1.Cells.Item($r, 2).Value2
    $r = $r+1
}

You're creating an empty array $Datastore = @() , and try to store data in the second index ( $i=1 , array index starts at zero, therefore index two). This causes an IndexOutOfRangeException .

Also $Total_Datastore = $Datastore1 + $Datastore2 + $Datastore3 + $Datastore4 doesn't make sense, since $Datastore1 (2,3 and 4) aren't defined anywhere.

Try:

 # Only integers are allowed
 $Data = [int] (Read-Host "Enter the count of Datastore")
 $ds = "-sm-"
 $Range1 = $Worksheetx1.Range("B1","B1048570")
 $Search1 = $Range1.find($ds)
 $r = $Search1.row

 $Datastore = @()
 for ($i=1; $i -le $Data; $i++) {
     # Todo: Check if $r is in a valid range or not !!!
     $Datastore += $Worksheetx1.Cells.Item($r, 2).Value2
     $r = $r+1
 }

 $Datastore

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM