且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何并行执行 PowerShell 函数多次?

更新时间:2023-11-24 11:33:40

不需要更新.定义一个脚本块并使用 Start-Job 根据需要多次运行脚本块.示例:

No update necessary for this. Define a script block and use Start-Job to run the script block as many times as necessary. Example:

$cmd = {
  param($a, $b)
  Write-Host $a $b
}

$foo = "foo"

1..5 | ForEach-Object {
  Start-Job -ScriptBlock $cmd -ArgumentList $_, $foo
}

脚本块采用 2 个参数 $a$b,它们由 -ArgumentList 选项传递.在上面的例子中,赋值是 $_$a$foo$b.$foo 只是一个可配置的静态参数示例.

The script block takes 2 parameters $a and $b which are passed by the -ArgumentList option. In the example above, the assignments are $_$a and $foo$b. $foo is just an example for a configurable, but static parameter.

运行 Get-Job |Remove-Job 在某个时候从队列中删除完成的作业(或 Get-Job | % { Receive-Job $_.Id; Remove-Job $_.Id } 如果您想检索输出).

Run Get-Job | Remove-Job at some point to remove the finished jobs from the queue (or Get-Job | % { Receive-Job $_.Id; Remove-Job $_.Id } if you want to retrieve the output).