首页 > 解决方案 > Powershell脚本将列表分解为多个数组

问题描述

我对 powershell 很陌生,我有一个同事帮助我构建的代码。它适用于一小组数据。但是,我将其发送到 SAP 业务对象查询,它只接受大约 2000 条数据。每个月我必须运行的数据量会有所不同,但通常约为 7000-8000 项。我需要帮助来更新我的脚本以运行数据列表创建一个数组,向其中添加 2000 个项目,然后使用接下来的 2000 个项目创建一个新数组,等等,直到它到达列表的末尾。

$source = "{0}\{1}" -f $ENV:UserProfile, "Documents\Test\DataSD.xls"

$WorkbookSource = $Excel.Workbooks.Open("$source")
$WorkSheetSource = $WorkbookSource.WorkSheets.Item(1)
$WorkSheetSource.Activate()
$row = [int]2
$docArray = @()
$docArray.Clear() |Out-Null

    Do
    {
        $worksheetSource.cells.item($row, 1).select() | Out-Null
        $docArray += @($worksheetSource.cells.item($row, 1).value())

        $row++
    }
    While ($worksheetSource.cells.item($row,1).value() -ne $null)

所以对于这个例子,我需要脚本来创建 4 个单独的数组。前 3 个将有 2000 个项目,最后一个将有 1200 个项目。

标签: arrayspowershell

解决方案


为此,您需要将数据导出到 CSV 或以其他方式将其提取到包含所有项目的集合中。使用类似 StreamReader 的东西可能会加快处理速度,但我从未使用过它。[脸红]

一旦$CurBatch生成,您可以将其输入到您想要的任何过程中。

$InboundCollection = 1..100
$ProcessLimit = 22
# the "- 1" is to correct for "starts at zero"
$ProcessLimit = $ProcessLimit - 1

$BatchCount = [math]::Floor($InboundCollection.Count / $ProcessLimit)

#$End = 0
foreach ($BC_Item in 0..$BatchCount)
    {
    if ($BC_Item -eq 0)
        {
        $Start = 0
        }
        else
        {
        $Start = $End + 1
        }

    $End = $Start + $ProcessLimit
    # powershell will happily slice past the end of an array
    $CurBatch = $InboundCollection[$Start..$End]

    ''
    $Start
    $End
    # the 1st item is not the _number in $Start_
    #    it's the number in the array @ "[$Start]"
    "$CurBatch"

    }

输出 ...

0
21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

22
43
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

44
65
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

66
87
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

88
109
89 90 91 92 93 94 95 96 97 98 99 100

推荐阅读