POWERSHELL / CHAPTER 13
Background jobs and isolated results
AdvancedTreat asynchronous work as a lifecycle with an output boundary.
By the end of this chapter
- Pass inputs explicitly to a background job
- Wait for and receive results deliberately
- Distinguish process jobs from shared-state assumptions
The idea
Start-Job runs work in a separate PowerShell process and returns a job object promptly. The job object describes ongoing work; it is not the function’s finished result. Pass required inputs explicitly with ArgumentList or an appropriate supported capture mechanism. Wait for completion and receive the result stream deliberately, while also considering failed state and error records rather than treating any returned object as proof of success.
Process jobs cross a serialization boundary, so many returned complex objects are deserialized data representations rather than live objects retaining every original method. They also do not provide ordinary shared mutable memory with the caller. After collecting what you need, remove the job resource. Thread-based alternatives have different sharing and isolation behavior; choose them consciously instead of assuming all background mechanisms have the same contracts.
$job = Start-Job -ScriptBlock { param($n) $n * 2 } -ArgumentList 4
try {
Receive-Job -Job $job -Wait
} finally {
Remove-Job -Job $job
}8
The input is passed to the job’s own process, Receive-Job waits for its output, and finally removes the completed job resource.
Try it yourself
Run two independent pure calculations as jobs, collect each outcome, and clean up both jobs even when one fails.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING