arrays - 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 个项目。
解决方案
为此,您需要将数据导出到 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
推荐阅读
- xcode - 有什么方法可以弱添加 Swift 包?
- powerbi - 为 Power BI 中的多个相似列创建单个切片器
- beautifulsoup - 来自 CoinMarketCap w 类的 Web Scraping Table
- jquery - 为什么来自 ajax 响应的模态调用没有关闭?
- r - FCT_Collapse 使用范围
- google-apps-script - Google App Script - 使用 fetch 循环以获取 API 响应并写入电子表格
- spyder - 有没有办法让 Spyder 的 IPython 控制台仅显示标准输出并在调试期间隐藏“IPdb”消息?
- javascript - 如何在构造函数中等待?
- integer - PromptForInteger 问题
- reactjs - 将 React 应用程序部署到 github 页面正在发布一个空白页面