【问题标题】:Index was outside the bounds of the array powershell索引超出了数组 powershell 的范围
【发布时间】:2019-07-16 03:59:25
【问题描述】:

我想从 Excel 工作表中获取多个数据。我收到错误是索引超出了数组的范围。

$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

【问题讨论】:

  • 通常,PoSh 在错误消息中提供更多信息。所以...您收到的完整错误消息是什么? - 请将该信息放入您的原始帖子中,而不是放入 cmets。
  • 您的代码没有意义,每次循环迭代都在重新定义$Datastore ....

标签: powershell


【解决方案1】:

问题在于这段代码:

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

您正在创建一个空数组$Datastore = @(),并尝试将数据存储在第二个索引中($i=1,数组索引从零开始,因此索引为二)。这会导致IndexOutOfRangeException

还有$Total_Datastore = $Datastore1 + $Datastore2 + $Datastore3 + $Datastore4 没有意义,因为$Datastore1(2,3 和 4)没有在任何地方定义。

试试:

 # 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

【讨论】:

  • 感谢您的快速回复。我已经使用了它正在工作的代码
  • @Ayyappa,谢谢。请将答案标记为正确 -> stackoverflow.com/help/someone-answers.
  • 我是第一次使用这个网站。请告诉我在哪里接受
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-30
  • 2015-04-19
  • 1970-01-01
  • 2015-11-06
  • 2010-11-17
相关资源
最近更新 更多