【问题标题】:Modify existing powershell script to use parallel processing修改现有的 powershell 脚本以使用并行处理
【发布时间】:2017-11-29 11:43:30
【问题描述】:

在将并行处理代码添加到此脚本时,我可以使用一些帮助。我想我只是对 powershell 的了解还不够,无法理解我在哪里以及在什么地方添加了必要的代码……我正在努力弄清楚,但灯泡还没有亮……:-)

Start-Transcript C:\temp\agent.log -IncludeInvocationHeader
$computers = gc "C:\temp\list.txt"
$source = "\\pathtodfsrootstore"
$dest = "c$\windows\temp\test2533212"

foreach ($computer in $computers) {
    foreach (if (Test-Connection -Cn $computer -count 1 -quiet) {
        Copy-Item -Force $source -Destination    \\$computer\$dest -Recurse
        #psexec.exe \\$computer cmd /c "c:\windows\temp\testv2533212\test.bat"
    } else {
        Write-output "$computer is not online"
    }
}
Stop-Transcript

【问题讨论】:

标签: powershell parallel-processing powershell-4.0


【解决方案1】:

我认为你可以这样做:

Start-Transcript C:\temp\agent.log -IncludeInvocationHeader

$Computers = Get-Content "C:\temp\list.txt"
$Source = "\\pathtodfsrootstore"
$Dest = "c$\windows\temp\test2533212"

$TestComputers = Test-Connection -Count 1 -AsJob $Computers
$TestResults = $TestComputers | Wait-Job | Receive-Job

$AliveComputers = ($TestResults | Where {$_.StatusCode -eq 0}).Address

Invoke-Command -ComputerName $AliveComputers -ScriptBlock {
    Copy-Item -Force $source -Destination c:\windows\temp\test2533212 -Recurse 
    & "c:\windows\temp\testv2533212\test.bat"
}

Stop-Transcript

这是一个两阶段的方法,我们使用 Test-Connection 的-AsJob 开关对所有计算机进行并行测试以找出哪些是活着的,然后使用这个结果来完成其他工作并行。

作业中的路径已更改,因为它们将在远程计算机上运行,​​因此可以引用本地路径。

我尚未对此进行测试,因此可能需要进行一些调整。您也可以忽略开头的 Test-Connection 部分,只允许作业在无法访问机器的地方失败。

使用上述解决方案,如果您想知道哪些机器无法访问,您可以这样做:

$DeadComputers = ($TestResults | Where {$_.StatusCode -ne 0}).Address

【讨论】:

  • 下午,非常感谢!我会在我们的测试区试一试,然后发回这里!!托尼
【解决方案2】:

对于并行处理,你可能想探索一下 powershell 工作流程,它有 foreach-parallel 组件,它将像魅力一样处理并行处理

Workflow basics

并行的一个sn-p如下

workflow Start-Something {

      foreach -Parallel($i in 0..1000)
      {
      $i
      }

      }

Start-Something

在上面的例子中for-each并行运行,powershell工作流程有一个限制,即我们不能有Write-Output,当你试图解决你的问题时,你可能想记录一下

p>

只是尝试在您的代码之上进行更改,您可能需要花费大约 15 分钟,尤其是您的解决方案,但要在这些行上工作

#Creating Workflow here ,
workflow Start-Something {

Start-Transcript C:\temp\agent.log -IncludeInvocationHeader
$computers = gc "C:\temp\list.txt"
$source = "\\pathtodfsrootstore"
$dest = "c$\windows\temp\test2533212"

foreach -Parallel($computer in $computers) {
if (Test-Connection -Cn $computer -count 1 -quiet) {
        Copy-Item -Force $source -Destination    \\$computer\$dest -Recurse
        #psexec.exe \\$computer cmd /c "c:\windows\temp\testv2533212\test.bat"
    } else {
       #You should log it somewhere
    }
}
Stop-Transcript
      }  


#Calling Workflow
Start-Something

【讨论】:

  • 下午,谢谢。也是这么看的!托尼
  • @TonyStrother 当然,看看编辑,并相应地工作,干杯:)
猜你喜欢
  • 2015-07-06
  • 2015-11-22
  • 2011-05-24
  • 1970-01-01
  • 2013-07-30
  • 2013-10-10
  • 2014-04-14
  • 2019-08-10
  • 1970-01-01
相关资源
最近更新 更多