PowerShell多線程執(zhí)行前后臺作業(yè)的例子
下面例子使用Powershell線程運(yùn)行了兩個后臺任務(wù)和一個前臺任務(wù),創(chuàng)建幾個運(yùn)行時間長點(diǎn)的任務(wù),并且每個任務(wù)命令中添加使用Start-Sleep。
$start = Get-Date
$task1 = { Start-Sleep -Seconds 4; Get-Service }
$task2 = { Start-Sleep -Seconds 5; Get-Service }
$task3 = { Start-Sleep -Seconds 3; Get-Service }
# run 2 in separate threads, 1 in the foreground
$thread1 = [PowerShell]::Create()
$job1 = $thread1.AddScript($task1).BeginInvoke()
$thread2 = [PowerShell]::Create()
$job2 = $thread2.AddScript($task2).BeginInvoke()
$result3 = Invoke-Command -ScriptBlock $task3
do { Start-Sleep -Milliseconds 100 } until ($job1.IsCompleted -and $job2.IsCompleted)
$result1 = $thread1.EndInvoke($job1)
$result2 = $thread2.EndInvoke($job2)
$thread1.Runspace.Close()
$thread1.Dispose()
$thread2.Runspace.Close()
$thread2.Dispose()
$end = Get-Date
Write-Host -ForegroundColor Red ($end - $start).TotalSeconds
相繼執(zhí)行這3個任務(wù)從Start-Sleep中看至少需要花費(fèi)12秒。但是這個腳本僅執(zhí)行了5秒多一點(diǎn)。其結(jié)果保存為$result1, $result2和$result3。與后臺作業(yè)對比,它在返回大數(shù)據(jù)用時將差不多。
文章出處:http://www.pstips.net/
相關(guān)文章
PowerShell腳本開發(fā)之對指定IP進(jìn)行端口掃描
在本文通過一段小腳本的方式引入了通過PowerShell實(shí)現(xiàn)簡單安全滲透功能的想法,首先介紹了該小腳本是如何實(shí)現(xiàn)功能的,接下來對創(chuàng)建腳本工具集并導(dǎo)入的方法,隨后又在該工具集中創(chuàng)建了Test-TCPPort函數(shù),并介紹了調(diào)用方法.2014-10-10PowerShell腳本清理指定天數(shù)前的臨時文件夾實(shí)現(xiàn)代碼
這篇文章主要介紹了PowerShell腳本清理指定天數(shù)前的臨時文件夾實(shí)現(xiàn)代碼,指定天數(shù)可以任意修改數(shù)字實(shí)現(xiàn),需要的朋友可以參考下2014-08-08PowerShell入門教程之創(chuàng)建和使用配置文件實(shí)例
這篇文章主要介紹了PowerShell入門教程之創(chuàng)建和使用配置文件實(shí)例,PowerShell的配置文件都是些普通的PowerShell腳本文件,需要的朋友可以參考下2014-10-10