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

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

问题描述

我有这样的PowerShell脚本:
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $某事]
[做某事]
[做某事]
}



<这样一个文件就被对方处理了。我想同时处理4个文件。



我知道foreach的并行循环,但是并行执行某些任务。我基本上想要并行运行整个foreach循环。



如何在PowerShell中实现这个功能?

解决方案

您可以查看工作 runspaces 。下面是一个工作例子:

$ p $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b[做某事]
}
#删除所有工作
Get-Job |删除作业
$ MaxThreads = 4
#启动作业。最多4个作业同时运行。
foreach($ file in $ files){
while($(Get-Job -state running).count -ge $ MaxThreads){
Start-Sleep -Milliseconds 3
}
Start-Job -Scriptblock $ Block -ArgumentList $ file
}
#等待所有工作完成。
while($(Get-Job -State Running).count -gt 0){
start-sleep 1
}
#获取每个作业的信息。
foreach(作业中的$ job){
$ info =接收作业-Id($ job.Id)
}
#删除所有创建的作业。
Get-Job | Remove-Job

在上面的代码中,每个 $ file 与其他人同时运行(最多同时运行4个)。

编辑:回应评论,这里是一些有关scriptblocks的文档。关于为什么必须包含该参数的一个简短原因是因为与PowerShell函数不同,scriptblocks不能在大括号之外指定参数。{/ b>

I have a PowerShell script like this:

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

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

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.

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

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

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

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