Powershell 可以并行运行命令吗? [英] Can Powershell Run Commands in Parallel?
问题描述
我有一个 powershell 脚本可以对一堆图像进行批处理,我想做一些并行处理.Powershell 似乎有一些后台处理选项,例如启动作业、等待作业等,但我发现用于并行工作的唯一好资源是编写脚本文本并运行它们(PowerShell 多线程)
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#...
推荐答案
您可以使用 后台工作.查看 Start-Job 和其他作业 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 "\$pipelinePassInc`$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屋!