PowerShell Remoting & Jobs
Two features let PowerShell do work somewhere else or at the same time: remoting runs commands on other computers, and jobs run commands in the background on your own computer. Both are central to managing many servers at once.
Remoting concepts
PowerShell remoting sends a script block to a remote computer, runs it there in a PowerShell session, and sends the objects back (serialised as XML, so they arrive as property-only "deserialised" copies without methods).
| Transport | Platforms | Setup |
|---|---|---|
| WinRM (WS-Management) | Windows | Enable-PSRemoting (on by default on Windows Server) |
| SSH | Windows, Linux, macOS | an SSH server with a pwsh subsystem |
The main commands:
| Command | Use |
|---|---|
Enter-PSSession -ComputerName srv01 |
interactive remote prompt, like ssh |
Invoke-Command -ComputerName a,b,c -ScriptBlock { … } |
run a block on many machines in parallel |
New-PSSession / Remove-PSSession |
keep a persistent connection to reuse |
-HostName user@srv01 |
use SSH instead of WinRM (PowerShell 7) |
PS> Invoke-Command -ComputerName web01, web02 -ScriptBlock {
>> Get-Service -Name W3SVC | Select-Object Status, Name
>> }
Status Name PSComputerName
------ ---- --------------
Running W3SVC web01
Stopped W3SVC web02
PS> Enter-PSSession -HostName ada@linux01 # SSH remoting
[ada@linux01]: PS /home/ada> uptime
[ada@linux01]: PS /home/ada> exit(Sample output; remoting needs real remote machines, so these commands aren't run here.) Each result gets a PSComputerName property telling you where it came from.
Invoke-Command without -ComputerName runs the block locally, which is a handy way to try the syntax, including passing arguments:
Invoke-Command -ScriptBlock { param($a, $b) "local run: $a + $b = $($a + $b)" } -ArgumentList 2, 3
$threshold = 80
try {
Invoke-Command -ScriptBlock { "threshold: $using:threshold" }
} catch { 'Locally, $using: is an error: it only works in remote sessions and jobs' }
Start-ThreadJob { "threshold seen inside a job: $using:threshold" } | Receive-Job -Wait -AutoRemoveJoblocal run: 2 + 3 = 5
Locally, $using: is an error: it only works in remote sessions and jobs
threshold seen inside a job: 80
On a remote computer, your local variables don't exist. Pass them with -ArgumentList or reference them as $using:name. $using: is only allowed where the block really runs somewhere else (a remote session, a job, ForEach-Object -Parallel), which is why the local Invoke-Command above rejects it and the thread job accepts it.
Background jobs
Start-Job runs a script block in a separate background PowerShell process. Your prompt returns immediately; collect the results later with Receive-Job:
$job = Start-Job -Name 'sum' -ScriptBlock {
$total = 0
foreach ($n in 1..1000) { $total += $n }
"sum = $total"
}
$job.Name
$finished = Wait-Job $job
$finished.State
Receive-Job $job
Remove-Job $jobsum
Completed
sum = 500500
| Cmdlet | Does |
|---|---|
Start-Job |
start a background job (separate process) |
Start-ThreadJob |
lighter job in a thread of the same process |
Get-Job |
list jobs and their State |
Wait-Job |
block until jobs finish (-Timeout seconds) |
Receive-Job |
get the output (-Keep to read it again later) |
Stop-Job / Remove-Job |
cancel / delete |
… & |
PowerShell 7: run a pipeline as a job, like in Bash |
Several jobs at once
Jobs shine when you have several slow, independent tasks. Start-ThreadJob is faster to start than Start-Job because it doesn't launch a new process:
$jobs = foreach ($site in 'alpha', 'beta', 'gamma') {
Start-ThreadJob -Name $site -ScriptBlock {
param($name)
Start-Sleep -Milliseconds 200 # pretend to do slow work
[pscustomobject]@{ Site = $name; Status = 'ok'; Length = $name.Length }
} -ArgumentList $site
}
$results = $jobs | Wait-Job | Receive-Job
$jobs | Remove-Job
$results | Sort-Object Site | Format-Table Site, Status, Length
Site Status Length
---- ------ ------
alpha ok 5
beta ok 4
gamma ok 5
All three jobs slept at the same time, so the whole thing took about 0.2 seconds instead of 0.6.
Errors and the & operator
A job's errors are kept with the job and appear when you receive it. In PowerShell 7 you can also put a job in the background by ending a pipeline with &:
$bad = Start-ThreadJob { 'partial output'; Write-Error 'something broke' }
$null = Wait-Job $bad
$bad.State
Receive-Job $bad -ErrorAction SilentlyContinue -ErrorVariable jobErrors
"errors: $($jobErrors.Count) -> $($jobErrors[0])"
$bg = 1..3 | ForEach-Object { $_ * 2 } &
$bg | Wait-Job | Receive-JobCompleted
partial output
errors: 1 -> something broke
2
4
6
Note: Background jobs created with
Start-Jobrun in a new process that does not load your session's variables, functions or modules. Pass what they need with-ArgumentList,$using:or-InitializationScript.
Test yourself
Which command runs a script block on several remote computers at once?
- Enter-PSSession
- Invoke-Command -ComputerName a, b, c
- Start-Job -ComputerName
- Receive-Job
How do you use the local variable $path inside a remote or job script block?
- $path
- $global:path
- $using:path
- $remote:path
Which cmdlet returns the output of a finished job?
- Get-Job
- Wait-Job
- Receive-Job
- Show-Job