在 powershell 中并行运行任务 [英] Running tasks parallel in powershell

查看:41
本文介绍了在 powershell 中并行运行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 PowerShell 脚本:

I have a PowerShell script like this:

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

这样一个文件一个接一个地处理.我想同时处理4个文件.

This way one file is treated after the other. I want to treat 4 files at the same time.

我知道 foreach -parallel 循环,但这会并行执行 [do something] 任务.我基本上想并行运行整个 foreach 循环.

I know of the foreach -parallel loop, but that does the [do something] tasks in parallel. I basically want to run the whole foreach loop in parallel.

如何在 PowerShell 中实现这一点?

How can I achieve this in PowerShell?

推荐答案

您可以查看 工作运行空间.以下是工作的示例:

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

在上面的代码中,每个 $file 都与彼此并行运行(最多 4 个同时运行).

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

响应评论,这里 是一些关于脚本块的文档.必须包含参数的简短原因是因为与 PowerShell 函数不同,脚本块不能在大括号 {} 之外指定参数.

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 {}.

这篇关于在 powershell 中并行运行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆