Job Manipulation
Receive-Job: retrieve output from existing jobGet-Job: query existing jobsRemove-Job: remove job from backgroundStop-Job: terminate the jobWait-Job: block the thread until one or all jobs are in a terminated state
Jobs has few identifier, such as name, id, instance id. All these cmdlet supports the corresponding parameters to specify the identity of jobs. They might not be pointed out explicitly for all sections
Parent & Child Jobs
Each background job has at least one child job, the parent job does not return or execute anything, child jobs takes the real work.
$job = sajb { foo }
$job.ChildJobs2
Job Type
BackgroundJobThreadJobRemoteJob
Querying Job
Get-Job returns all parent background jobs by default.
-IncludeChildJob: list both parent jobs and child jobs, you might notice the job id is successive.-ChildJobState: filter by child job state-Command: get all jobs that executes a command satisfies the pattern in literal.ps1gjb -Command 'gps *'1-State: get all jobs with specific state.ps1gjb -State Completed,Running1-Name: get by job name- ...
Remove Job
Remove-Job is not interesting and various, its parameters are pretty similar to Get-Job and it's commonly used together with Get-Job too.
gjb | rjb # remove all jobTerminate Job
Stop-Job, has the same form as Remove-Job, to terminate a running job.
Retrieve Job Result
Receive-Job returns all results from the child jobs of a job. The return type of job result is not certain. It depends on the action you specified.
-Name: retrieve result from given job name-Id: retrieve result from given job id-Job: retrieve result from given job object, positional-Keep: preserve the job object after inspectionps1rcjb $job -Keep # some result rcjb $job # some result, consumed here # rcjb $job # no result # $job -eq $null # False, the object is still available1
2
3
4-Wait: synchronously block the thread to wait for the job to complete and finally get the result.ps1rcjb $job -Wait # session blocked # result here1
2
Wait for Job
Wait-Job can wait for jobs until they reach a terminated state like Completed, Failed, Stopped, Suspended, Disconnected
-Any: wait until any job terminated-Timeout: wait until timeout were reached-Force: wait forSuspendedandDisconnected
Wait-Job or Receive-Job -Wait
You may be confused about Wait-Job and Receive-Job -Wait; They both wait for jobs, but Wait-Job respects the order of how jobs were created while Receive-Job only collects by order of completion time.
Wait-Job waits for all child jobs to complete without collecting anything, so the order remains, finally Receive-Job retrieve the result by that order. Direct Receive-Job collects immediately when each job is completed, so the order is random.
# this is always sorted
1..10 | foreach -Parallel { echo $_ } -AsJob | wjb | rcjb # 1 2 3 4 5 .. 10
# this has random order
1..10 | foreach -Parallel { echo $_ } -AsJob | rcjb -Wait2
3
4