Posted By

itsvetkov on 01/26/11


Tagged

job parallel


Versions (?)

Parallel “For Each”


 / Published in: Windows PowerShell
 

  1. ParallelForEach-Object(
  2. [ScriptBlock] $Script = { param([Object] $Data) Write-Output $Data },
  3. [Int] $Threads = 0
  4. )
  5. {
  6.  
  7. begin {
  8. $Jobs = @()
  9. if ($Threads -eq 0) {
  10. Get-WmiObject Win32_Processor | ForEach-Object { $Threads = $Threads + $_\3.NumberOfLogicalProcessors }
  11. }
  12. Write-Host "Executing $Threads thread(s)"
  13. }
  14.  
  15. process {
  16. # Write-Host 'Number of jobs:' $Jobs.Length
  17. if ($Jobs.Length -ge $Threads) {
  18. # Write-Host 'Waiting for any job to complete'
  19. $CompletedJob = Wait-Job $Jobs -Any
  20. $Jobs = $Jobs -ne $CompletedJob
  21. Receive-Job $CompletedJob
  22. Remove-Job $CompletedJob
  23. }
  24. $Jobs = $Jobs + (Start-Job $Script -ArgumentList $_\3)
  25. }
  26.  
  27. end {
  28. while ($Jobs.Length -gt 0) {
  29. $CompletedJob = Wait-Job $Jobs -Any
  30. $Jobs = $Jobs -ne $CompletedJob
  31. Receive-Job $CompletedJob
  32. Remove-Job $CompletedJob
  33. }
  34. }
  35.  
  36. }

Report this snippet  

You need to login to post a comment.