Powershell可以并行运行命令吗? [英] Can Powershell Run Commands in Parallel?

查看:198
本文介绍了Powershell可以并行运行命令吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个powershell脚本可以对一堆图像进行一些批处理,并且我想进行一些并行处理. Powershell似乎具有一些后台处理选项,例如start-job,wait-job等,但是我发现进行并行工作的唯一好资源是编写脚本文本并运行它们(

I have a powershell script to do some batch processing on a bunch of images and I'd like to do some parallel processing. Powershell seems to have some background processing options such as start-job, wait-job, etc, but the only good resource I found for doing parallel work was writing the text of a script out and running those (PowerShell Multithreading)

理想情况下,我想要类似于.net 4中的并行foreach的东西.

Ideally, I'd like something akin to parallel foreach in .net 4.

有点像什么的东西:

foreach-parallel -threads 4 ($file in (Get-ChildItem $dir))
{
   .. Do Work
}

也许我最好还是下降到C#...

Maybe I'd be better off just dropping down to c#...

推荐答案

您可以使用开始作业和其他作业cmdlet.

You can execute parallel jobs in Powershell 2 using Background Jobs. Check out Start-Job and the other job cmdlets.

# Loop through the server list
Get-Content "ServerList.txt" | %{

  # Define what each job does
  $ScriptBlock = {
    param($pipelinePassIn) 
    Test-Path "\\$pipelinePassIn\c`$\Something"
    Start-Sleep 60
  }

  # Execute the jobs in parallel
  Start-Job $ScriptBlock -ArgumentList $_
}

Get-Job

# Wait for it all to complete
While (Get-Job -State "Running")
{
  Start-Sleep 10
}

# Getting the information back from the jobs
Get-Job | Receive-Job

这篇关于Powershell可以并行运行命令吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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