How to execute a PowerShell function several times in parallel?

后端 未结 5 1265
情歌与酒
情歌与酒 2020-12-05 00:30

I\'m not sure whether to call this a need for multi-threading, job-based, or async, but basically I have a Powershell script function that takes several parameters and I nee

5条回答
  •  借酒劲吻你
    2020-12-05 00:49

    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
    }
    

    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.

    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).

提交回复
热议问题