Powershell加速后台作业


后台作业将很好提高脚本效率,因为他们能并行处理任务。总归,如果你的数据不是很繁琐后台作业将是不错的选择,因为通过XML回传数据通常会比通过多线程获得数据要花费更多的时间。

幸运的是你可以控制数据返回的情况,请看。

这段代码同时跑了3个任务($code1-3).其中两个运行在后台,一个运行在当前Powershell中。

$start = Get-Date

$code1 = { Get-Hotfix }
$code2 = { Get-ChildItem $env:windir\system32\*.dll }
$code3 = { Get-Content -Path C:\Windows\WindowsUpdate.log }

$job1 = Start-Job -ScriptBlock $code1 
$job2 = Start-Job -ScriptBlock $code2
$result3 = & $code3 

$alljobs = Wait-Job $job1, $job2 

Remove-Job -Job $alljobs
$result1, $result2 = Receive-Job $alljobs

$end = Get-Date
$timespan = $end - $start
$seconds = $timespan.TotalSeconds
Write-Host "This took me $seconds seconds."
This takes about half a minute. When you run all three jobs sequentially and do not use background jobs, they just take 5 seconds.

$start = Get-Date

$result1 = Get-Hotfix 
$result2 = Get-ChildItem $env:windir\system32\*.dll 
$result3 = Get-Content -Path C:\Windows\WindowsUpdate.log 

$end = Get-Date
$timespan = $end - $start
$seconds = $timespan.TotalSeconds
Write-Host "This took me $seconds seconds."
So background jobs really have made the code more complex and increased the script runtime. Only when you start and optimize the return data will background jobs become useful. The fewer data they emit, the better.

$start = Get-Date

$code1 = { Get-Hotfix | Select-Object -ExpandProperty HotfixID }
$code2 = { Get-Content -Path C:\Windows\WindowsUpdate.log | Where-Object { $_ -like '*successfully installed*' }}
$code3 = { Get-ChildItem $env:windir\system32\*.dll | Select-Object -ExpandProperty Name }

$job1 = Start-Job -ScriptBlock $code1 
$job2 = Start-Job -ScriptBlock $code2
$result3 = & $code3 

$alljobs = Wait-Job $job1, $job2 

Remove-Job -Job $alljobs
$result1, $result2 = Receive-Job $alljob

这次,后台作业将返回更多的所需数据,并且将这些输出显示到Powershell前端宿主。这次将减少大量的执行时间。

通常,后台作业将更好的做一些简单的事情(例如一个配置文档)而又不需要返回什么数据或只返回一点点数据。

原文地址:Speeding Up Background Jobs

×用微信扫描并分享
本文链接: https://www.pstips.net/speeding-up-background-jobs.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

发表评论

邮箱地址不会被公开。 必填项已用*标注