Cmdlets can perform their action internally or as a Windows PowerShell background job. When a cmdlet runs as a background job, the work is done asynchronously in its own thread separate from the pipeline thread that the cmdlet is using. From the user perspective, when a cmdlet runs as a background job, the command prompt returns immediately even if the job takes an extended amount of time to complete, and the user can continue without interruption while the job runs.
Jobs, Child Jobs, and the Job Repository
The job object that is returned by the cmdlets that support jobs defines the job (the Start-Job cmdlet also returns a job object). The name of the job, an identifier that is used to specify the job, the state information, and the child jobs are included in this definition. The job does not perform any of the work. Each job has at least one child job because the child job performs the actual work. When you run a cmdlet so that the work is performed as a job, the cmdlet must add the job and the child jobs to a common repository, referred to as the job repository.
For more information about how jobs are handled at the command line, see the following:
Writing a Cmdlet That Runs as a Job
To write a cmdlet that can be run as a job, you must include the following functionality:
Define an asJob switch parameter so that the user can decide whether to run the cmdlet as a job.
Create an object that derives from the Job class. This object can be a custom job object or a job object provided by Windows PowerShell, such as a PSEventJob object.
In a record processing method, add an if statement that detects whether the cmdlet should run as a job.
For custom job objects, implement the job class.
Return the appropriate objects based on whether the cmdlet is run as a job.
For a code example, see How to Support Jobs.
The following APIs are provided by Windows PowerShell to manage background jobs.
- An abstract class used to derive custom job objects.
- Manages and provides information about the current active jobs.
- Defines the state of the job. States include Started, Running, and Stopped.
- Provides information about the state of a job and, if the last state change was due to an error, the reason the job entered its current state.
- Provides the arguments for an event that is raised when a job changes state.
Windows PowerShell Job Cmdlets
The following cmdlets are provided by Windows PowerShell to manage background jobs.
- Gets Windows PowerShell background jobs that are running in the current session.
- Gets the results of the Windows PowerShell background jobs in the current session.
- Deletes a Windows PowerShell background job.
- Starts a Windows PowerShell background job.
- Stops a Windows PowerShell background job.
- Suppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are complete.
Other ResourcesWriting a Windows PowerShell Cmdlet