为了账号安全,请及时绑定邮箱和手机立即绑定

Powershell可以并行运行命令吗?

Powershell可以并行运行命令吗?

Powershell可以并行运行命令吗?我有一个powershell脚本对一堆图像进行一些批处理,我想做一些并行处理。Powershell似乎有一些后台处理选项,如启动作业,等待作业等,但我找到的并行工作的唯一好资源是编写脚本文本并运行它们(PowerShell多线程)理想情况下,我喜欢类似于.net 4中的并行foreach的东西。有点像:foreach-parallel -threads 4 ($file in (Get-ChildItem $dir)){    .. Do Work}也许我会更好的只是下降到c#...
查看完整描述

3 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

您可以使用后台作业在Powershell 2中执行并行作业。查看Start-Job和其他作业cmdlet。

# Loop through the server listGet-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 completeWhile (Get-Job -State "Running"){
  Start-Sleep 10}# Getting the information back from the jobsGet-Job | Receive-Job


查看完整回答
反对 回复 2019-08-16
?
LEATH

TA贡献1936条经验 获得超6个赞

史蒂夫汤森的回答在理论上是正确的,但在实践中却没有,正如@likwid指出的那样。我修改后的代码考虑了工作环境障碍 -默认情况下没有任何障碍超越这个障碍!因此,自动$_变量可以在循环中使用,但不能直接在脚本块中使用,因为它位于作业创建的单独上下文中。

要将变量从父上下文传递到子上下文,请使用-ArgumentList参数on 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 completeWhile (Get-Job -State "Running") { Start-Sleep 2 }# Display output from all jobsGet-Job | Receive-Job# CleanupRemove-Job *

(我通常喜欢提供PowerShell文档的参考作为支持证据,但是,唉,我的搜索没有结果。如果您碰巧知道上下文分离的记录,请在此发表评论以告诉我!)


查看完整回答
反对 回复 2019-08-16
  • 3 回答
  • 0 关注
  • 863 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信