Powershell可以并行运行命令吗?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (40)

我有一个Powershell脚本来对一堆图像进行批处理,我想做一些并行处理。Powershell似乎有一些后台处理选项,比如启动作业、等待作业等等,但是我找到的唯一的并行工作资源是编写脚本文本并运行

理想情况下,我希望类似于.NET 4中的并行程序。

一些看起来不太像的东西:

foreach-parallel -threads 4 ($file in (Get-ChildItem $dir))
{
   .. Do Work
}
提问于
用户回答回答于
# 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
用户回答回答于

若要将变量从父上下文传递到子上下文,请使用-ArgumentList参数上Start-Job发送并使用param在脚本块内接收它。

cls
# Send in two root directory names, one that exists and one that does not.
# Should then get a "True" and a "False" result out the end.
"temp", "foo" | %{

  $ScriptBlock = {
    # accept the loop variable across the job-context barrier
    param($name) 
    # Show the loop variable has made it through!
    Write-Host "[processing '$name' inside the job]"
    # Execute a command
    Test-Path "\$name"
    # Just wait for a bit...
    Start-Sleep 5
  }

  # Show the loop variable here is correct
  Write-Host "processing $_..."

  # pass the loop variable across the job-context barrier
  Start-Job $ScriptBlock -ArgumentList $_
}

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

# Display output from all jobs
Get-Job | Receive-Job

# Cleanup
Remove-Job *

扫码关注云+社区

领取腾讯云代金券