Powershell后臺作業(yè)、異步操作實(shí)例
Powershell是單線程程序且一次只能做一件事情。后臺作業(yè)能額外增加Powershell進(jìn)程在后臺處理作業(yè)。當(dāng)需要程序同時運(yùn)行且數(shù)據(jù)量不是很大時它能很好的解決問題。但從Powershell后臺回傳數(shù)據(jù)是一個非常麻煩的工作,它將浪費(fèi)很多時間。將會導(dǎo)致腳本更慢。
這里有3個并發(fā)執(zhí)行任務(wù):
$start = Get-Date
# get all hotfixes
$task1 = { Get-Hotfix }
# get all scripts in your profile
$task2 = { Get-Service | Where-Object Status -eq Running }
# parse log file
$task3 = { Get-Content -Path $env:windir\windowsupdate.log | Where-Object { $_ -like '*successfully installed*' } }
# run 2 tasks in the background, and 1 in the foreground task
$job1 = Start-Job -ScriptBlock $task1
$job2 = Start-Job -ScriptBlock $task2
$result3 = Invoke-Command -ScriptBlock $task3
# wait for the remaining tasks to complete (if not done yet)
$null = Wait-Job -Job $job1, $job2
# now they are done, get the results
$result1 = Receive-Job -Job $job1
$result2 = Receive-Job -Job $job2
# discard the jobs
Remove-Job -Job $job1, $job2
$end = Get-Date
Write-Host -ForegroundColor Red ($end - $start).TotalSeconds
上面執(zhí)行全部的任務(wù)消耗了5.9秒。三個任務(wù)的結(jié)果將分別存入$result1, $result2, 和 $result3.
讓我們再繼續(xù)查看相繼在前臺執(zhí)行完命令需要多長時間:
$start = Get-Date
# get all hotfixes
$task1 = { Get-Hotfix }
# get all scripts in your profile
$task2 = { Get-Service | Where-Object Status -eq Running }
# parse log file
$task3 = { Get-Content -Path $env:windir\windowsupdate.log | Where-Object { $_ -like '*successfully installed*' } }
# run them all in the foreground:
$result1 = Invoke-Command -ScriptBlock $task1
$result2 = Invoke-Command -ScriptBlock $task2
$result3 = Invoke-Command -ScriptBlock $task3
$end = Get-Date
Write-Host -ForegroundColor Red ($end - $start).TotalSeconds
結(jié)果,這次只花費(fèi)了5.05秒。與后臺作業(yè)幾乎同時完成,所以后臺作業(yè)更適合解決長時間執(zhí)行的任務(wù)。從三個任務(wù)返回的數(shù)據(jù)觀察,好處是這種按順數(shù)在前臺獲得數(shù)據(jù)能減少了執(zhí)行過程的開銷。
相關(guān)文章
PowerShell 語音計(jì)算器實(shí)現(xiàn)代碼
帶中文發(fā)音功能的計(jì)算器程序,支持鼠標(biāo)和小鍵盤輸入,支持多種數(shù)值轉(zhuǎn)人民幣的相關(guān)資料2017-10-10
Powershell實(shí)現(xiàn)監(jiān)測服務(wù)器連通狀態(tài)
這篇文章主要介紹了Powershell實(shí)現(xiàn)監(jiān)測服務(wù)器連通狀態(tài),代碼很簡單,本文直接給出實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-05-05
Windows Powershell分析和比較管道結(jié)果
這篇文章主要介紹了Windows Powershell分析和比較管道結(jié)果,需要的朋友可以參考下2014-09-09
powershell 將文本轉(zhuǎn)換成表格的另一種可行方式
這篇文章主要介紹了powershell 將文本轉(zhuǎn)換成表格的另一種可行方式,需要的朋友可以參考下2014-08-08
PowerShell中調(diào)用外部程序和進(jìn)程操作命令例子
這篇文章主要介紹了PowerShell中調(diào)用外部程序和進(jìn)程操作命令例子,給出了進(jìn)程操作的一些命令和調(diào)用外部應(yīng)用程序的方法,需要的朋友可以參考下2014-08-08
Powershell小技巧之使用-F方法帶入數(shù)據(jù)
這篇文章主要介紹了Powershell的一個使用-F方法帶入數(shù)據(jù)的小技巧,非常的簡單,也很易懂,記錄一下分享給大家2014-09-09
PowerShell中實(shí)現(xiàn)混淆密碼示例
這篇文章主要介紹了PowerShell中實(shí)現(xiàn)混淆密碼示例,本文給出了混淆密碼的例子和使用混淆后的密碼例子,需要的朋友可以參考下2015-03-03

