我有一个 powershell 脚本来对一堆图像进行一些批处理,我想做一些并行处理。 Powershell 似乎有一些后台处理选项,例如启 Action 业、等待作业等,但我发现用于并行工作的唯一好的资源是编写脚本文本并运行它们( PowerShell Multithreading )
理想情况下,我想要类似于 .net 4 中的并行 foreach 的东西。
一些看起来很不起眼的东西,例如:
foreach-parallel -threads 4 ($file in (Get-ChildItem $dir))
{
.. Do Work
}
也许我最好直接转向 c#...
最佳答案
您可以使用 Background Jobs 在 Powershell 2 中执行并行作业。查看Start-Job以及其他作业 cmdlet。
# 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
关于multithreading - Powershell 可以并行运行命令吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4016451/