国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PowerShell > 正文

Powershell后臺作業、異步操作實例

2020-05-30 20:10:13
字體:
來源:轉載
供稿:網友

Powershell是單線程程序且一次只能做一件事情。后臺作業能額外增加Powershell進程在后臺處理作業。當需要程序同時運行且數據量不是很大時它能很好的解決問題。但從Powershell后臺回傳數據是一個非常麻煩的工作,它將浪費很多時間。將會導致腳本更慢。

這里有3個并發執行任務:
代碼如下:
$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

上面執行全部的任務消耗了5.9秒。三個任務的結果將分別存入$result1, $result2, 和 $result3.
讓我們再繼續查看相繼在前臺執行完命令需要多長時間:

代碼如下:
$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

結果,這次只花費了5.05秒。與后臺作業幾乎同時完成,所以后臺作業更適合解決長時間執行的任務。從三個任務返回的數據觀察,好處是這種按順數在前臺獲得數據能減少了執行過程的開銷。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 云南省| 上虞市| 托克托县| 巴彦县| 海南省| 兴义市| 新竹县| 尚义县| 望都县| 牙克石市| 武清区| 五峰| 苍溪县| 潢川县| 通化县| 黄大仙区| 灵川县| 钟山县| 沁水县| 清水县| 杨浦区| 饶平县| 白银市| 郓城县| 金阳县| 页游| 金昌市| 凤冈县| 洛扎县| 密山市| 鄱阳县| 浏阳市| 柳江县| 东安县| 新兴县| 镇赉县| 深圳市| 阳高县| 景东| 宾阳县| 同德县|