【发布时间】:2019-07-15 11:24:09
【问题描述】:
我正在尝试在 Powershell Core 中运行一些脚本(没有工作流,没有 ForEach 的 -Parallel 选项)。
所以我试图分批拆分我的数组并并行运行它们。所以我这样做:
$iterCount = 150000;
$threadCount = 8;
$batchSize = $iterCount/$threadCount;
$block = {
Param($range)
Foreach ($i in $range) {
...
}
}
For ($i = 0; $i -lt 150000; $i += $batchSize) {
Start-Job -Scriptblock $block -ArgumentList $i..$i+$batchSize
}
但是当我调用它时,我得到了
Start-Job : Cannot bind parameter 'InitializationScript'. Cannot convert the ".. 0+18750" value of type "System.String" to type "System.Management.Automation.Scr iptBlock".
At /home/tchain/dit/push_messages3.ps1:63 char:48
+ Start-Job -Scriptblock $block -ArgumentList $i..$i+$batchSize
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-Job], ParameterBindingExce ption
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Co mmands.StartJobCommand
似乎ArgumentList 将所有内容都字符串化,因此我无法传递范围。
有没有办法传递强类型范围?有没有更好的方法来并行化循环?我想写(0..150000).AsParallel().ForEach($i => ...) 但是好像写不出来。
我使用Param([int] $from, [int] $to) 作为解决方法,但我不确定这是否是我能做的最好的。
【问题讨论】:
标签: powershell