Chapters/scripting-at-scale/scaling-backgroundjobs.ps1


<#
$a = {1..1111}
$b = {2..2111}
$c = {3..3333}

$all=@()
$all+= foreach ($item in ($a,$b,$c)) {
 start-job -ScriptBlock $item
}

write-host "Waiting for items to complete"
$all | Wait-job | receive-job | measure

$all=@()
$all += &$a
$all += &$b
$all += &$c
$all | measure
#>



#create a big list
$computers = 1..5 | foreach {get-content C:\scripts\servers.txt}

$computers.count

#using nothing 52 sec
#85 items 4:45
measure-command { 
 $all = foreach ($item in $computers) {
    test-wsman $item
}
}

#using background jobs 56 sec
#85 items 4:32
measure-command {
$all=@()
$all+= foreach ($item in $computers) {
 start-job {test-wsman $item}
}
$all | Wait-job | receive-job -Keep
}

#using runspaces 10sec
#85 items 16 seconds
measure-Command {
$rspace = @()
foreach ($item in $computers) {
    $run = [powershell]::Create()
    $run.AddCommand("test-wsman").addparameter("computername",$item)
    $handle = $run.beginInvoke()
    $run | Add-member -MemberType NoteProperty -Name Handle -Value $handle
    $rspace+=$run
}

<#
While ($rspace.invocationStateInfo.state -contains "running") {
 #loop and wait
}
#>


While (-Not $rspace.handle.isCompleted) {}

#get results
$results=@()
for ($i = 0;$i -lt $rspace.count;$i++) {
$results+= $rspace[$i].EndInvoke($rspace[$i].handle)
}

$rspace.ForEach({$_.dispose()})

}