随笔 - 911  文章 - 5  评论 - 94  阅读 - 243万

多线程异步执行脚本

 

获取远程计算机信息:

复制代码
 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

posted on   momingliu11  阅读(1071)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示