Search notes:

PowerShell cmdLet receive-job

receive-job collects the result («output») of background jobs that were started with start-job or cmdlets using the -asJob parameter.

Starting a background job and printing its result

The following simplistic example starts a job in the background that calculates the 17th triangular number (153).
In order to pretend that this is a difficult calculation, the job uses start-sleep so that the job is not immediately finished.
After starting the job, the script goes on to do an unrelated task. Every once in a while, it checks the background job's state. If it has finished ($job.state -eq 'Completed) and there is a result ($job.hasMoreData), it collects the result and prints it:
$job = start-job {
 #
 # Calculate the 17th triangular number.
 #
   $result = 0;
   foreach ($i in 1 .. 17) {
      $result += $i
   }

   return $result
 #
 # Pretend it's a real difficult calculation that
 # takes some time …
 #
   start-sleep 6

   return $result
}


foreach ($j in 1 .. 10) {
 #
 # Do something different while the
 # calculation runs in the background
 #

   write-host "j = $j"

   if ($job.state -eq 'Completed') {

      if ($job.hasMoreData) {
        $t17 = receive-job $job
        write-host "Calculated result = $t17"
      }

   }

   start-sleep 2
}
Github repository about-PowerShell, path: /cmdlets/job/receive/show-result.ps1

See also

Powershell command noun: job

Index