Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 34 ยท Real-World Use

Remoting, Jobs and Parallelism

Run PowerShell on other machines with Enter-PSSession, Invoke-Command and SSH, and run work in the background with Start-Job, thread jobs and ForEach-Object -Parallel.

One machine is rarely the whole story. You may need to check disk space on forty servers, restart a service on a remote host, or process a thousand files without waiting for them one by one. PowerShell has two families of tools for this: remoting, which runs commands on other computers, and jobs and parallelism, which run work in the background or side by side on the same computer.

Both need real machines, processes and networks, so the PowerShell commands here are read-only. The runnable examples are JavaScript stand-ins: a promise-based model of jobs, a deterministic simulation of throttled parallel work, and a demonstration of why remote results are copies. They show the ideas and the rules, not the real engine.

Where does the work run?

Remoting On another computer, over WinRM or SSH.
Jobs In the background, in a child process.
Thread jobs In the background, in a lightweight thread.
-Parallel Side by side inside one pipeline.

Pick the lightest tool that fits.

1 / 2

Remoting: running commands elsewhere

PowerShell remoting sends a script block to another machine, runs it there, and brings back the results. There are two transports:

  • WinRM (WS-Management) is the classic one for Windows computers. On the target you enable it once from an elevated session with Enable-PSRemoting. It is built into Windows PowerShell and PowerShell 7 on Windows.
  • SSH works on Windows, Linux and macOS with PowerShell 6 and later. The target needs an SSH server configured with a PowerShell subsystem, and you connect with -HostName instead of -ComputerName.
POWERSHELL
# Interactive: the prompt changes to show the remote computer
Enter-PSSession -ComputerName server01
[server01]: PS C:\> Get-Service W32Time
[server01]: PS C:\> Exit-PSSession

# One-off, on several machines at once
Invoke-Command -ComputerName server01, server02 -ScriptBlock {
    Get-Volume -DriveLetter C | Select-Object DriveLetter, SizeRemaining
}

# SSH transport (PowerShell 7)
Enter-PSSession -HostName linux01 -UserName deploy
Invoke-Command -HostName linux01 -UserName deploy -ScriptBlock { uname -a }

# Reuse a connection for several commands
$s = New-PSSession -ComputerName server01
Invoke-Command -Session $s -ScriptBlock { Get-Date }
Remove-PSSession $s

Invoke-Command against several computers runs them in parallel (up to a throttle limit of 32 connections by default, adjustable with -ThrottleLimit) and adds a PSComputerName property to every result, so you can tell where each came from.

The script block runs in a separate session on the remote computer, with none of your local variables. Pass values with -ArgumentList or read local variables with the $using: prefix:

POWERSHELL
$threshold = 10GB
Invoke-Command -ComputerName server01 -ScriptBlock {
    Get-Volume | Where-Object SizeRemaining -lt $using:threshold
}

Access is controlled by the permissions of the account you connect with, and non-domain machines may need extra setup (such as trusted hosts or certificates), so involve whoever owns the network before opening up remoting.

Results are copies

Objects cross the network as a serialized description and are rebuilt on your side. You get the property values, but they are no longer live objects: methods are gone, and the type is a deserialized copy. A process object from Get-Process on a remote machine cannot be asked to Kill(); call Stop-Process remotely instead.

JS Why remote objects lose their methods

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JSON is only an illustration. PowerShell uses its own serialization (XML based over WinRM, JSON-like over SSH) and keeps a type name on the copy such as Deserialized.System.ServiceProcess.ServiceController, but the consequence is the same: data survives, behavior does not.

Background jobs with Start-Job

Start-Job runs a script block in a separate PowerShell process in the background and returns a job object at once, so your prompt is free.

POWERSHELL
$job = Start-Job -ScriptBlock { Start-Sleep 5; Get-ChildItem C:\Windows -File | Measure-Object Length -Sum }
Get-Job                       # State: Running, Completed, Failed
Wait-Job $job                 # block until it finishes
Receive-Job $job              # collect the output (and clear it)
Remove-Job $job

Rules that surprise people:

  • The job has no access to your variables or functions. Use -ArgumentList or $using:.
  • Receive-Job removes the output it returns unless you add -Keep. A second call returns nothing.
  • Results are deserialized copies, as with remoting, because a job is a separate process.
  • Jobs live only as long as your session; if you close PowerShell, running jobs end.
  • Starting a process is slow (a fraction of a second or more), so jobs pay off for work measured in seconds, not milliseconds.

The model below imitates the job lifecycle with promises: start several jobs, check states, wait, receive, and see that receiving clears the output.

JS A Start-Job, Wait-Job, Receive-Job model

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the states: all three are Running right after starting, and the third ends as Failed, where real PowerShell also records the reason on the job. The first Receive-Job used -Keep, so the second call still saw the data; the third call found it gone. The model uses a toy promise delay in place of a process, and ignores process start-up cost.

Thread jobs

Start-ThreadJob runs the script block in a thread inside your current process. It starts much faster and uses less memory than Start-Job, and it works with the same Get-Job, Wait-Job and Receive-Job cmdlets. It is included with PowerShell 7; in Windows PowerShell 5.1 you install the ThreadJob module from the PowerShell Gallery. Its default -ThrottleLimit is 5 running jobs, and others queue.

POWERSHELL
$jobs = 1..10 | ForEach-Object { Start-ThreadJob -ScriptBlock { param($n) $n * $n } -ArgumentList $_ }
$jobs | Wait-Job | Receive-Job

Because threads share the process, a crash or a runaway job affects the whole session, while a separate-process job is better isolated.

ForEach-Object -Parallel

PowerShell 7 added -Parallel to ForEach-Object: each input item is processed by the script block in its own runspace, several at the same time.

POWERSHELL
$urls = 'https://example.com/a', 'https://example.com/b', 'https://example.com/c'
$urls | ForEach-Object -Parallel {
    $response = Invoke-WebRequest $_ -Method Head -TimeoutSec 10
    [pscustomobject]@{ Url = $_; Status = $response.StatusCode }
} -ThrottleLimit 3

The details that matter:

  • -ThrottleLimit caps simultaneous runspaces; the default is 5.
  • Variables from outside need the $using: prefix, and they arrive as copies you should treat as read-only. To collect results safely, emit objects (as above) instead of writing to a shared list.
  • The output order is not guaranteed. Items that finish first are emitted first. Sort afterwards if order matters.
  • Creating a runspace has a cost, so tiny, fast work gets slower in parallel. Use it for slow, independent operations such as network calls or heavy file work.

The simulation below uses a virtual clock (no real waiting) to show a throttle limit at work: eight tasks with different durations, run with limits 1, 3 and 5.

JS Simulating -ThrottleLimit with a virtual clock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With limit 1 the work is sequential and the output keeps input order. With higher limits the total time drops, but never below the longest single task, and the output order follows finishing time, not input order. The simulation hands each task to whichever worker is free first, which is a reasonable picture of a throttled pool, though real scheduling has start-up costs and timing jitter.

Choosing between them

Need Tool
Run on other computers Invoke-Command (WinRM or SSH), Enter-PSSession to explore
A long task you will collect later, isolated Start-Job
Many quick background tasks in one process Start-ThreadJob
Process a list with concurrency in one pipeline ForEach-Object -Parallel
Parallel work on remote machines Invoke-Command with a list of computers

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You run Invoke-Command -ComputerName srv01 -ScriptBlock { Get-Date -Date $cutoff } and $cutoff is a local variable. What happens?

    The script block runs in a separate session on the remote machine, with none of your variables. Pass the value with $using: or -ArgumentList.
  2. 2. What is true about objects returned from a remote computer?

    Objects are serialized for the trip and rebuilt as copies. To act on the remote object, run the action in the remote script block.
  3. 3. You call Receive-Job twice on the same finished job without -Keep. What does the second call return?

    Receive-Job returns and removes the job's output unless -Keep is used.
  4. 4. Which statement about ForEach-Object -Parallel is correct?

    -Parallel exists in PowerShell 7 and later, defaults to five concurrent runspaces and emits results as they complete.
  5. 5. Which tool starts its work in a separate PowerShell process?

    Start-Job uses a child process, which isolates it but costs start-up time. Thread jobs and -Parallel use threads or runspaces inside the current process.

Summary

  • Remoting runs script blocks on other computers over WinRM (-ComputerName) or SSH (-HostName); Invoke-Command can target many machines at once and tags results with PSComputerName.
  • Remote and job output arrive as copies: values yes, methods no. Pass variables in with -ArgumentList or $using:.
  • Start-Job uses a separate process; Receive-Job clears output unless -Keep is given.
  • Start-ThreadJob is a lighter, thread-based alternative with a default limit of 5 running jobs.
  • ForEach-Object -Parallel (PowerShell 7+) runs items concurrently, defaults to five at a time, and does not preserve output order.
  • Parallel work helps with slow, independent operations, and the longest task sets the minimum time.

Next, call web services from scripts in Web Requests and REST APIs.