🎓 A1Learner
🔍
0 of 46 lessons completed

PowerShell Remoting Jobs

A remoting job is a remote command that runs in the background. Its result is collected later, instead of waiting for it to finish.

A remoting job cannot start locally

AsJob asks for a background job on a remote host. With no host given, the parameter set cannot resolve.

try { $j = Invoke-Command -ScriptBlock { 1 + 1 } -AsJob -ErrorAction Stop; Receive-Job $j -Wait } catch { "Caught: " + $_.Exception.Message }

A named host fails on the missing service

Adding a host name does not fix the missing service. The message names WSMan again.

try { $j = Invoke-Command -ComputerName "localhost" -ScriptBlock { 1 + 1 } -AsJob -ErrorAction Stop; Receive-Job $j -Wait } catch { "Caught: " + $_.Exception.Message }

The local pattern works with Start-Job

Start-Job runs a block in the background on this machine. Receive-Job with Wait collects its result.

$j = Start-Job -ScriptBlock { 3 + 4 }
$r = Receive-Job $j -Wait
"Local job: $r"

Example

try { $j = Invoke-Command -ScriptBlock { 5 + 5 } -AsJob -ErrorAction Stop; Receive-Job $j -Wait } catch { "Caught: " + $_.Exception.Message }
$j2 = Start-Job -ScriptBlock { "apple"; "banana" }
$r = Receive-Job $j2 -Wait | Sort-Object
"Local job: " + ($r -join ", ")

Key points

  • Background job: work that runs on its own while the main script carries on.
  • Use Invoke-Command with AsJob to ask for a remote command as a background job.
  • Use Receive-Job to collect the result of a finished job.
  • Use Wait with Receive-Job to pause until the job finishes.
  • A remoting job needs a remote host, so it cannot start on this machine alone.

In this example, the first block tries a remoting job and catches its failure. The second block starts the same kind of work with Start-Job instead. Receive-Job collects the local result, and sorting gives a fixed order for the two words.

Note

Start-Job runs the same background pattern locally, without a remote host.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Receive-Job do?