欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Powershell后臺作業(yè)、異步操作實例

 更新時間:2014年04月16日 11:38:48   作者:  
如果需要加快執(zhí)行一個腳本,你可能需要用到后臺作業(yè)。后臺作業(yè)能同時運行腳本中多個事件

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

這里有3個并發(fā)執(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 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í)行全部的任務消耗了5.9秒。三個任務的結果將分別存入$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

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

相關文章

最新評論