multithreading - Powershell GUI, Progress Bar, and Hash Tables -
part of script i'm working on takes specified username, searches active directory computers named username, pings them, , adds online machines array use later. i'd add progress bar ping portion of script i'm running problems. form have present progress bar freezes execution of script if invoke prior ping loop.
here code progress bar (pretty basic):
#progress bar $objformpbar = new-object system.windows.forms.form $objformpbar.text = "loading" $objformpbar.size = new-object system.drawing.size(200,100) $objformpbar.startposition = "centerscreen" $objformpbar.topmost = $true $objformpbar.icon = $icon $progressbar = new-object system.windows.forms.progressbar $progressbar.size = new-object system.drawing.size(175,20) $progressbar.location = new-object system.drawing.size(5, 20) $progressbar.minimum = 0 $progressbar.maximum = 0 $objformpbar.controls.add($progressbar)
here i'm attempting display it, way halts execution of script (called inside click handler function, global variables):
$global:progressbar.maximum = $computers.count $global:objformpbar.add_shown({$objformpbar.activate()}) [void] $global:objformpbar.showdialog() foreach ($computer in $computers) { $computer = $computer.trim() if(test-connection $computer -count 1) { $arraycomputers.add($computer) | out-null } $global:progressbar.increment(1) } $global:objformpbar.close()
looking problem i've discovered can run progress bar in separate thread , pass variables between 2 (see: marquee progress bar freezes in powershell ). have had no luck getting work or thread launch. how can progress bar , form along run in thread?
why don't use built-in ui reporting progress in powershell? it's 1 line call write-progress
e.g.:
$computers = 1..10 | % {"server$_"} $numcomputers = $computers.length ($ndx = 0; $ndx -le $numcomputers; $ndx++) { $computer = $computers[$ndx].trim() write-progress "testing connection $computer" -percentcomplete ($ndx/$numcomputers * 100) #if (test-connection $computer -count 1) { # $arraycomputers.add($computer) | out-null #} start-sleep -seconds 1 }
btw primary problem approach above showdialog()
method call doesn't return until form closed. if want use showdialog(), have execute logic in context of event handler inside form (load/activate). other option use show()
means you'll have pump messages in loop using application.doevents() form have chance update itself.
Comments
Post a Comment