Advertisement
filimonic

PowerShell RSJob Template

Sep 13th, 2020 (edited)
1,858
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function SomeFunction
  2. {
  3.     Param(
  4.        [String]$SampleParam
  5.     )
  6.     return $SampleParam.ToUpper()
  7. }
  8.  
  9. $JobScript = [scriptblock]{
  10.     $inQueue = [System.Collections.Concurrent.ConcurrentQueue[string]]$args[0]
  11.     $outBag = [System.Collections.Concurrent.ConcurrentBag[string]]$args[1]
  12.     $currentItem = $null
  13.     while($inQueue.TryDequeue([ref] $currentItem) -eq $true)
  14.     {
  15.         try
  16.         {
  17.             # Add result to OutBag
  18.             $result = SomeFunction -SampleParam $currentItem -EA Stop
  19.             $outBag.Add( $result )
  20.         }
  21.         catch
  22.         {
  23.             # Catch error
  24.             Write-Output $_.Exception.ToString()
  25.         }
  26.     }
  27. }
  28.  
  29. $inData = [System.Collections.Concurrent.ConcurrentQueue[string]]::new(
  30.     [String[]](@(1..10000) | % { return [guid]::NewGuid().ToString() }) # Sample strings in lower case
  31.     )
  32.  
  33. $resultData = [System.Collections.Concurrent.ConcurrentBag[string]]::new()
  34.  
  35. # Wait for queue to empty
  36. $i_cur = $inData.Count
  37. $i_max = $i_cur
  38.  
  39. # Start jobs
  40. $jobs = @(1..20) | % { Start-RSJob -ScriptBlock $JobScript -ArgumentList @($inData, $resultData) -FunctionsToImport @('SomeFunction') }
  41.  
  42. # Wait queue to empty
  43. while($i_cur -gt 0)
  44. {
  45.     Write-Progress -Activity 'Doing job' -Status "$($i_cur) left of $($i_max)" -PercentComplete (100 - ($i_cur / $i_max * 100))
  46.     Start-Sleep -Seconds 3 # Update frequency
  47.     $i_cur = $inData.Count
  48. }
  49.  
  50. # Wait jobs to complete
  51. $logs = $jobs | % { Wait-RSJob -Job $_ } | % { Receive-RSJob -Job $_  }
  52. $jobs | % { Remove-RSJob -Job $_ }
  53. $Global:resultData = $resultData
  54. $Global:logs = $logs
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement