I'm trying to run some script in Powershell Core (no workflow, no -Parallel option for ForEach).
So I'm trying to split my array in batches and run them at parallel. So I do:
$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
}
But when I call it I get
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
It seems that ArgumentList
stringifies everything so I cannot pass a range.
Is there a way to pass strongly typed range? Is there any better way to parallelize loop? I'd like to write (0..150000).AsParallel().ForEach($i => ...)
But it seems that I can't.
I did Param([int] $from, [int] $to)
as a workaround, but I'm not sure if it's the best I can do.