Jobs are a in many ways the key to Powershell multithreading. Having jobs running in the background not only allows you to keep working in your console while your script is silently churning away in the background, but it also lets you run multiple commands or scripts simultaneously executed from console.
When to use jobs
Whenever you’d like to run a command or a scriptblock without locking up your console, or when you’d like to run multiple commands simultaneously. Jobs are “fire and forget” tasks that you don’t review until they’ve completed or failed.
When not to use jobs
When running basic administration tasks where you’re reviewing output or the result of command continuously, or when working with result sets in variables where you’d like to keep reviewing the current value of the variable.
Ways to use jobs
There are two ways of using jobs in Powershell. First of all, many cmdlets have the parameter “-AsJob” to allow them run in the background directly. Alternatively you can use the cmdlet Start-Job to initiate a job with any cmdlet of combination of commands.
-AsJob
Some cmdlets that has the -AsJob parameter are:
Get-WmiObject
Invoke-Command
Invoke-WmiMethod
Remove-WmiObject
Restart-Computer
Set-WmiInstance
Stop-Computer
Test-Connection
If you like to find a more complete list, use the following command.
1 |
Get-Command -ParameterName asjob |
NB. Keep in mind that you need to load the modules your looking for commands in, in advance. Module autoloading doesn’t work when looking for parameters (Tested with Powershell 5.0 in Windows 10 Technical Preview)
Cmdlets
There are 4 cmdlets that are key to using Powershell jobs:
Start-Job
Starts a background job to execute one or more Powershell commands.
1 2 3 4 5 6 7 8 9 |
Start-Job -Name GetChildItem -ScriptBlock {Get-ChildItem -Name *.exe -Path C:\Windows -Recurse} Start-Job -Name TestNetconnection -ScriptBlock { $servers = "localhost","www.boldevin.com" foreach ($server in $servers) { Test-NetConnection $server -CommonTCPPort RDP Test-NetConnection $server -CommonTCPPort WINRM Test-NetConnection $server -CommonTCPPort HTTP } } |
Get-Job
Collects and lists the running and completed jobs currently in memory
1 2 3 4 |
Get-Job -Id 24 Get-Job -Name GetServices Get-Job -State Completed Get-Job | Where Location -eq localhost |
Receive-Job
Presents the result of a job to screen, or otherwise lets you collect or manipulate the result
1 2 3 |
Receive-Job -Id 58 -Keep Receive-Job -Name GetServices -Keep $result = Receive-Job -ID 22 |
Remove-Job
Removes one or more jobs from memory
1 |
Remove-Job -Id 4 |
Other useful cmdlets:
Suspend-Job: Pauses a job
.
Resume-Job: Resumes a paused job.
Stop-Job: Stops a job
.
Wait-Job: Suspends the command prompt until a job is finished, preventing you from making the input.