Running tasks in parallel in powershell

I have a PowerShell script like this:

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

Thus, one file is processed after another. I want to process 4 files at a time.

I know a parallel foreach loop, but it does parallel tasks [do something]. I basically want to run the foreach loop in parallel.

How can I achieve this in PowerShell?

+4
source share
2 answers

You can see Jobs or runspaces . Here is an example of Work:

$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 one $fileworks in parallel with eachother (up to 4 starts simultaneously).

EDIT: . , , , PowerShell {}.

+9

Get-Help about_Foreach-Parallel, ForEach -Parallel... , ( , Parallel {...}). script PowerShell, ; Parallel Sequence .

+2

Source: https://habr.com/ru/post/1675935/


All Articles