多线程异步执行脚本

 

获取远程计算机信息:

$d=get-date
$servers="10.4.34.41","10.4.34.40","10.4.34.36","10.4.34.37","10.4.34.39"
$serverpass="Dell1950"
$UserName="Administrator"

#定义线程数量
$throttleLimit = 5
$SessionState = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
$Pool = [runspacefactory]::CreateRunspacePool(1, $throttleLimit, $SessionState, $Host)
$Pool.Open()

#脚本块
$ScriptBlock = {
param($server,$serverpass,$username)
$Password = ConvertTo-SecureString $serverpass -AsPlainText –Force
$cred = New-Object System.Management.Automation.PSCredential($UserName,$Password)
$cs = gwmi win32_computersystem -computer $server -Credential $cred
$cs.Name
}


$threads = @()
$handles = foreach ($server in $servers) {
$powershell = [powershell]::Create().AddScript($ScriptBlock).AddArgument($server).AddArgument($serverpass).AddArgument($username)
$powershell.RunspacePool = $Pool
$powershell.BeginInvoke()
$threads += $powershell
}


do {
$i = 0
$done = $true
foreach ($handle in $handles)
{
if ($handle -ne $null)
{
if ($handle.IsCompleted)
{
$threads[$i].EndInvoke($handle)
$threads[$i].Dispose()
$handles[$i] = $null
}
else {$done = $false}
}
$i++
}
if (-not $done) { Start-Sleep -Milliseconds 500 }
} until ($done)

New-TimeSpan $d

 

==============================

进度提示:

function Start-Progress {
  param(
    [ScriptBlock]
    $code
  )
   
  $newPowerShell [PowerShell]::Create().AddScript($code)
  $handle $newPowerShell.BeginInvoke()
   
  while ($handle.IsCompleted -eq $false) {
    Write-Host ‘.‘ -NoNewline
    Start-Sleep -Milliseconds 500
  }
   
  Write-Host ‘‘
   
  $newPowerShell.EndInvoke($handle)
   
  $newPowerShell.Runspace.Close()
  $newPowerShell.Dispose()
}

From:http://www.pstips.net/speeding-up-powershell-multithreading.html

多线程异步执行脚本,布布扣,bubuko.com

多线程异步执行脚本

上一篇:spring aop理解


下一篇:Windows性能监控perfmon工具的使用和性能指标的分析