多线程异步执行脚本
获取远程计算机信息:
1 $d=get-date 2 $servers="10.4.34.41","10.4.34.40","10.4.34.36","10.4.34.37","10.4.34.39" 3 $serverpass="Dell1950" 4 $UserName="Administrator" 5 6 #定义线程数量 7 $throttleLimit = 5 8 $SessionState = [system.management.automation.runspaces.initialsessionstate]::CreateDefault() 9 $Pool = [runspacefactory]::CreateRunspacePool(1, $throttleLimit, $SessionState, $Host) 10 $Pool.Open() 11 12 #脚本块 13 $ScriptBlock = { 14 param($server,$serverpass,$username) 15 $Password = ConvertTo-SecureString $serverpass -AsPlainText –Force 16 $cred = New-Object System.Management.Automation.PSCredential($UserName,$Password) 17 $cs = gwmi win32_computersystem -computer $server -Credential $cred 18 $cs.Name 19 } 20 21 22 $threads = @() 23 $handles = foreach ($server in $servers) { 24 $powershell = [powershell]::Create().AddScript($ScriptBlock).AddArgument($server).AddArgument($serverpass).AddArgument($username) 25 $powershell.RunspacePool = $Pool 26 $powershell.BeginInvoke() 27 $threads += $powershell 28 } 29 30 31 do { 32 $i = 0 33 $done = $true 34 foreach ($handle in $handles) 35 { 36 if ($handle -ne $null) 37 { 38 if ($handle.IsCompleted) 39 { 40 $threads[$i].EndInvoke($handle) 41 $threads[$i].Dispose() 42 $handles[$i] = $null 43 } 44 else {$done = $false} 45 } 46 $i++ 47 } 48 if (-not $done) { Start-Sleep -Milliseconds 500 } 49 } until ($done) 50 51 New-TimeSpan $d
==============================
进度提示:异步线程
1 function Start-Progress { 2 param( 3 [ScriptBlock] 4 $code 5 ) 6 7 $newPowerShell = [PowerShell]::Create().AddScript($code) 8 $handle = $newPowerShell.BeginInvoke() 9 10 while ($handle.IsCompleted -eq $false) { 11 Write-Host '.' -NoNewline 12 Start-Sleep -Milliseconds 500 13 } 14 15 Write-Host '' 16 17 $newPowerShell.EndInvoke($handle) 18 19 $newPowerShell.Runspace.Close() 20 $newPowerShell.Dispose() 21 }
From:http://www.pstips.net/speeding-up-powershell-multithreading.html