Running tasks parallel in powershell

后端 未结 3 1604
有刺的猬
有刺的猬 2020-12-05 14:40

I have a PowerShell script like this:

Foreach ($file in $files) {
    [Do something]
    [Do something]
    [Do something]
}

This way one f

3条回答
  •  借酒劲吻你
    2020-12-05 15:15

    You might look into Jobs or runspaces. Here is an example of Jobs:

    $block = {
        Param([string] $file)
        "[Do something]"
    }
    #Remove all jobs
    Get-Job | Remove-Job
    $MaxThreads = 4
    #Start the jobs. Max 4 jobs running simultaneously.
    foreach($file in $files){
        While ($(Get-Job -state running).count -ge $MaxThreads){
            Start-Sleep -Milliseconds 3
        }
        Start-Job -Scriptblock $Block -ArgumentList $file
    }
    #Wait for all jobs to finish.
    While ($(Get-Job -State Running).count -gt 0){
        start-sleep 1
    }
    #Get information from each job.
    foreach($job in Get-Job){
        $info= Receive-Job -Id ($job.Id)
    }
    #Remove all jobs created.
    Get-Job | Remove-Job
    

    In the above code I have it where each $file is running in parallel with eachother (Up to 4 running simultaneously).

    EDIT: In response to the comments, here is some documentation about scriptblocks. The short reason about why you must include the parameter is because unlike PowerShell functions, scriptblocks can't specify parameters outside of the braces {}.

提交回复
热议问题