PowerShell Lesson 6: Remoting, Jobs and Parallel Administration

From “run this on one machine” to “run this on two hundred machines, safely and fast”: how remoting moves commands and objects across the wire, how to fan out with Invoke-Command, reuse sessions, use SSH on every OS, run work in background jobs and parallel runspaces without race conditions, handle credentials and the double hop, delegate with JEA, schedule unattended runs — and finish with OpsKit v0.4's parallel health check
PowerShell 7.6 LTS (7.6.10)WinRM loopback + SSHLocal only · FreeVerified · 2026-11-24
Position in the Learning Path Lessons 1–5 worked on one machine in one runspace: objects and the pipeline (1), the language (2), advanced functions and the first OpsKit functions (3), packaging OpsKit as a module (4), and robust error handling with Invoke-OpsBackup in OpsKit v0.3 (5). This lesson scales out: the same objects now travel to other computers (and come back deserialized), run in other processes (jobs) and in other threads (-Parallel). The milestone is OpsKit v0.4: Invoke-OpsHealthCheck checks every server from Get-OpsServer in parallel with per-server timeouts and timing, verified against real local endpoints. Lesson 7 then points the same tooling at REST APIs and the cloud. The Bash course did this with ssh host cmd, &/wait and xargs -P; you will see where PowerShell is similar and where objects change the picture.
Overall Learning Objectives
  • Explain the two remoting transports — WinRM (WS-Management, 5985/5986, Kerberos/NTLM) and SSH (the pwsh -sshs subsystem) — and what a session configuration (endpoint) is, including why plain Invoke-Command -ComputerName on Windows lands in Windows PowerShell 5.1 unless you ask for PowerShell.7.
  • Predict what comes back from any remote call or process job: deserialized property bags (Deserialized.* type names, no methods) — this lesson's core animation, “a FileInfo crossing the wire”.
  • Fan out with Invoke-Command: -ThrottleLimit (default 32), $using:, PSComputerName, collecting per-computer errors without losing the good results, -AsJob and -HideComputerName.
  • Reuse connections with New-PSSession (measured: 10 calls in 287 ms instead of 6.7 s), keep state, copy files with Copy-Item -ToSession/-FromSession, disconnect and reconnect (WinRM only) and use implicit remoting.
  • Set up and use SSH remoting across Windows, Linux and macOS (-HostName, -UserName, -KeyFilePath, the Subsystem powershell line) and recognize its typical failures.
  • Choose between Start-Job (process, deserialized, slow start), Start-ThreadJob (thread, live objects) and remote jobs; manage job states, Receive-Job -Keep, Wait-Job -Timeout and failed vs “completed with errors”.
  • Use ForEach-Object -Parallel correctly: -ThrottleLimit (default 5), $using:, functions are not visible, -TimeoutSeconds, -AsJob — and prove a lost-update race and its fix with concurrent collections.
  • Handle credentials without plaintext, explain the double hop and its options (CredSSP, resource-based Kerberos constrained delegation, JEA), author JEA files, and schedule pwsh -NoProfile -NonInteractive -File with Task Scheduler, cron or systemd timers.

1-Hour Time Allocation

#TimeModuleCore ContentAnimation / InteractiveLab (~/pslab)
0Before ClassRemoting lab targetsRead-only checks: Test-WSMan, WinRM/sshd services, session configurations, ThreadJob module; choose loopback, a Linux container or a VM; OpsKit v0.3 in ~/pslab/OpsKitEnvironment self-check checklistDecide which remoting labs you can run for real
100–06Remoting architectureWinRM vs SSH, ports and authentication, endpoints (microsoft.powershell = 5.1 vs PowerShell.7), runspaces on the remote side, CLIXML serialization, rehydrated vs deserialized typescore animation: a FileInfo crossing the wireSerialize a FileInfo locally, through a job and through loopback remoting
206–13Invoke-Command fan-out-ComputerName arrays, -ThrottleLimit, $using:, PSComputerName, -ErrorVariable per computer, -AsJob, -HideComputerNameFan-out simulator with throttling and failuresMeasure ThrottleLimit 6 vs 2 on loopback
313–21SessionsNew-PSSession, reuse, state, Enter-PSSession, Copy-Item -ToSession, Disconnect/Connect/Receive-PSSession, implicit remotingSession lifecycleTen calls: fresh vs reused session; copy a file both ways
421–28SSH remoting-HostName, -UserName, -KeyFilePath, -Options, sshd Subsystem, Windows OpenSSH, Linux/macOS, containersSSH connection path: where it failsDiagnose “subsystem request failed”
528–35JobsStart-Job vs Start-ThreadJob (Microsoft.PowerShell.ThreadJob), job states, Receive-Job -Keep / -Wait -AutoRemoveJob, Wait-Job -Timeout / -Any, Stop-JobJob state machineMeasure start-up cost; failed vs completed-with-errors
635–42ParallelismForEach-Object -Parallel, throttle, $using:, functions not visible, -TimeoutSeconds, -AsJob, runspace reuse, races, ConcurrentDictionary/ConcurrentBagLost-update race, step by stepReproduce a race (251 of 500) and fix it
742–50Security and schedulingPSCredential, no plaintext, SecretManagement, double hop (reproduced), CredSSP risks, RBKCD, JEA role capabilities and session configurations, Task Scheduler, cron, systemd timersDouble-hop ticket flowAuthor JEA files and a scheduled-task object (nothing registered)
850–60OpsKit v0.4Invoke-OpsHealthCheck: pipeline input, -Parallel with module import per runspace, per-server timeout, result objects with timings; local TCP endpoints + unreachable 10.x serversHealth-check run + troubleshooting tree17 servers checked in 2.5 s
—After ClassCheat sheet · Integrated labCompare sequential vs ThreadJob vs -Parallel health checks with Measure-Command and a correctness checkFinal quiz (12 questions)21.7 s → 4.0 s → 2.4 s, identical verdicts

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLab
Choose a transport and endpoint✓✓✓✓··✓·Test-WSMan, -ConfigurationName PowerShell.7, -HostNameM1, M4
Predict serialization✓✓✓·✓✓·✓PSSerializer, Export-Clixml, pstypenamesM1, M5
Fan out and collect errors per target·✓✓····✓Invoke-Command -ThrottleLimit -ErrorVariable, PSComputerNameM2
Reuse sessions and copy files··✓✓····New-PSSession, Copy-Item -ToSession, Receive-PSSessionM3
Run background jobs✓✓✓·✓✓·✓Start-Job, Start-ThreadJob, Receive-Job, Wait-JobM5, integrated lab
Parallelize safely····✓✓·✓ForEach-Object -Parallel, ConcurrentDictionaryM6, M8, integrated lab
Handle credentials and delegation✓··✓··✓·Get-Credential, New-PSRoleCapabilityFile, New-PSSessionConfigurationFileM7
Schedule unattended runs····✓·✓✓New-ScheduledTask*, cron, systemd timer, pwsh -NoProfile -NonInteractive -FileM7

Excluded from this lesson (and where to learn it)

TopicWhy not in this lessonWhere to learn it
Enabling remoting on servers, WinRM HTTPS listeners and certificates, Group Policy for WinRM, firewall rulesMachine configuration; this lesson changes no machine state and explains the settings insteadWS-Management remoting docs; the Windows Server course material
CIM/WMI sessions (New-CimSession, Get-CimInstance -ComputerName)A different remoting stack (WS-Man/DCOM, CIM objects) with its own modelMicrosoft Learn: about_CimSession
Desired State Configuration, Ansible's psrp/winrm connectionConfiguration management, not ad-hoc administrationAnsible course
Runspace pools written by hand ([runspacefactory]::CreateRunspacePool(), [powershell]::Create())-Parallel and ThreadJob cover the same need with less codeParallel execution article
Secrets in vaults in depth (SecretManagement, SecretStore, Azure Key Vault), REST APIsCloud automationLesson 7
Pester tests for OpsKit (mocking Test-OpsEndpoint), CIQuality and releaseLesson 8

How to use these materials

10 pages per module
Principles · Diagram · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. Module 1's serialization animation is the thread of the whole lesson: jobs, sessions and OpsKit results all cross a boundary.
Real vs expected
Everything labelled “Actual output (7.6.10)” was run on a Windows 11 lab machine where WinRM loopback already worked. Steps that would change machine state (enabling remoting, editing sshd_config, registering tasks or JEA endpoints) are shown as “Expected output” and listed in Known limitations.
Progress and voice
A quiz score of 70% or more, or “Mark this module complete”, counts toward progress (stored in this browser). The “Voice” tab reads the narration with the browser's Web Speech API.
Version notes Verified 2026-11-24 on PowerShell 7.6.10 (.NET 10.0.15), Windows 11, domain-joined, WinRM running with an HTTP listener. PowerShell 7.6 ships Microsoft.PowerShell.ThreadJob 2.2.0, which replaces the old ThreadJob module (the command is still Start-ThreadJob; its module-qualified name changed). ForEach-Object -Parallel exists since 7.0; runspace reuse became the default in 7.1 (-UseNewRunspace opts out). SSH remoting needs PowerShell 6+ on both ends; -Options for SSH arrived in 7.3. Windows PowerShell 5.1 has WinRM remoting, Start-Job and (as a Gallery download) ThreadJob, but no -Parallel and no SSH remoting.

Module 0 · Prep: remoting lab targets (localhost, SSH, containers)

Find out — with read-only commands — which remoting labs your machine can run for real, pick a target for the SSH labs, and confirm that OpsKit v0.3 from Lesson 5 loads
Before class ≈ 10 minRead-only checksChanges nothing on the machine
Prerequisites
  • Lessons 1–5, especially pipeline binding (1), advanced functions (3), modules (4) and error handling (5). ~/pslab/data generated by New-LabData.ps1.
  • PowerShell 7.6 on Windows, Linux or macOS. For the WinRM parts you need Windows with WinRM already enabled (Windows Server enables it by default; Windows 11 clients do not). Without it, read those outputs and do the jobs and -Parallel labs, which run everywhere.
  • Only administer machines you own or are authorized to manage. Every lab here targets your own machine or a throw-away container/VM.

Warm-up: answer from memory (30 seconds)

1. In Lesson 5, why does Invoke-OpsBackup use [CmdletBinding(SupportsShouldProcess)]?

So callers get -WhatIf and -Confirm for free and the function can ask $PSCmdlet.ShouldProcess() before each change. You will rely on this again: fan-out makes mistakes 200 times bigger.

2. What does -ErrorAction Stop do to a non-terminating error?

It turns it into a terminating error that try/catch can catch. In Module 2 you will see that on a fan-out this also discards the results of the computers that worked.

3. Which binding mode lets Import-Csv servers.csv | Some-Command fill -Name and -IP?

ByPropertyName (Lesson 1). Invoke-OpsHealthCheck takes whole objects ByValue instead and reads IP, Port or HealthUrl from each one.

Choose your remoting targets

TargetWhat you needUsed in
A. Windows loopback over WinRM (localhost)WinRM service running with a listener (Test-WSMan localhost succeeds) and you are a local administrator or in Remote Management Users. Enabling it is a one-time admin change (Enable-PSRemoting) — do it only on a lab machine; this lesson's runs did not need it because it was already enabled.M1–M3, M7 (real outputs in this lesson)
B. Linux container with PowerShell + sshdDocker; an image built from mcr.microsoft.com/powershell:lts with openssh-server and the Subsystem powershell line (Module 4 shows the Dockerfile). Disposable: delete it after class.M4 (cross-platform SSH)
C. A lab VM (Windows Server or Linux)Hyper-V/VirtualBox/cloud VM you own; SSH key or domain accountM2–M4 with a real second machine; M7 double hop
D. No remoting at allNothingM5, M6, M8 and the integrated lab run entirely locally (jobs, threads, 127.0.0.1 endpoints)

Read-only checks

$PSVersionTable.PSVersion.ToString()
Get-Service WinRM, sshd -ErrorAction SilentlyContinue | Format-Table Name, Status, StartType
Test-WSMan localhost                       # does a WinRM listener answer?
Get-PSSessionConfiguration | Format-Table Name, PSVersion   # needs an elevated session
Get-Module -ListAvailable Microsoft.PowerShell.ThreadJob | Format-Table Name, Version
7.6.10

Name   Status StartType
----   ------ ---------
sshd  Running Automatic
WinRM Running Automatic

wsmid           : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor   : Microsoft Corporation
ProductVersion  : OS: 0.0.0 SP: 0.0 Stack: 3.0

Name              PSVersion
----              ---------
PowerShell.7      7.6
PowerShell.7.6.0  7.6
PowerShell.7.6.10 7.6
PowerShell.7.6.3  7.6
PowerShell.7.6.5  7.6
PowerShell.7.6.6  7.6
PowerShell.7.6.8  7.6
PowerShell.7.6.9  7.6

Name                           Version
----                           -------
Microsoft.PowerShell.ThreadJob 2.2.0

Read it like this: WinRM answers (so loopback labs can run), sshd is running (Module 4 will show it is not configured for PowerShell), and pwsh registered a PowerShell.7 endpoint plus one per installed patch version — every MSI upgrade that registers endpoints adds another PowerShell.7.6.x. Get-PSSessionConfiguration in pwsh lists only PowerShell 7 endpoints; Windows PowerShell's microsoft.powershell endpoint is still there and is the default (Module 1). If Test-WSMan fails with “The client cannot connect to the destination…”, WinRM is not enabled: use targets B–D.

Confirm OpsKit v0.3 and the data

Set-Location ~/pslab
Import-Module ./OpsKit/OpsKit.psd1 -Force
Get-Command -Module OpsKit | Sort-Object Name | Format-Table Name, Version
(Get-OpsServer -Path ./data/servers.csv).Count
Name             Version
----             -------
Get-OpsConfig    0.3.0
Get-OpsServer    0.3.0
Invoke-OpsBackup 0.3.0
Test-OpsEndpoint 0.3.0

12

This lesson only relies on this interface: Get-OpsServer returns objects with Name, Env, IP and Port (8080 for the CSV inventory). Module 8 replaces Test-OpsEndpoint with a v0.4 version (millisecond timeout, never throws) and adds Invoke-OpsHealthCheck; both files are printed in full, so you can follow along even if your Lesson 3–5 code differs.

Environment self-check checklist

Risks and cleanup Nothing in this lesson enables remoting, edits sshd_config, changes TrustedHosts, opens firewall ports, registers scheduled tasks or JEA endpoints, or stores credentials — those steps are shown as text. Labs write only under ~/pslab/tmp, start listeners on 127.0.0.1 only, and every lab ends with a cleanup step (Remove-PSSession, Get-Job | Remove-Job -Force, Stop-LabEndpoint). If a lab is interrupted, run Get-PSSession | Remove-PSSession; Get-Job | Remove-Job -Force.

Module 1 · Remoting architecture: WinRM vs SSH, sessions and serialization

00:00 – 06:00 · A remote command runs in a runspace on the other machine; your script block travels there as text, and the results travel back as XML — so what you get back looks like the original object but is a property bag without methods
6 minWinRM loopback · PSSerializer · Start-Job★★★★★ core
Learning objectives
  • Describe both transports: WinRM (WS-Management over HTTP 5985 / HTTPS 5986, Kerberos or NTLM, Windows-first) and SSH (port 22, keys or passwords, any OS, PowerShell runs as an sshd subsystem).
  • Explain session configurations (endpoints) and prove that the default WinRM endpoint on Windows is microsoft.powershell = Windows PowerShell 5.1, while -ConfigurationName PowerShell.7 reaches pwsh 7.6.
  • Predict the result of serialization: primitive and a few well-known types are rehydrated; everything else comes back as Deserialized.<Type> with properties only, and nested .NET objects below the depth become strings.
  • Reproduce all of this locally with [PSSerializer], Export-Clixml and Start-Job.
Prerequisites: Module 0; Lesson 1 (objects, Get-Member). Importance:★★★★★ (every “it works locally but not remotely” bug in this lesson is a serialization or endpoint question)

What: one protocol (PSRP), two transports

PowerShell remoting is the PowerShell Remoting Protocol (PSRP): the client creates a runspace pool on the server, sends pipelines (your script block as text plus arguments), and receives output, errors, warnings, progress and host calls as serialized messages. PSRP itself does not care how bytes move; two transports carry it:

WinRM (WS-Management)SSH
Parameters-ComputerName, -Credential, -UseSSL, -ConfigurationName, -Authentication-HostName, -UserName, -KeyFilePath, -Port, -Subsystem, -Options (7.3+)
Port5985 (HTTP; payload still encrypted by Kerberos/NTLM message encryption) / 5986 (HTTPS)22
AuthenticationKerberos in a domain; NTLM (Negotiate) otherwise, which requires TrustedHosts or HTTPS for non-domain targets; CredSSP, certificatesSSH keys (recommended) or password; Kerberos via GSSAPI where configured
Server sideWinRM service → wsmprovhost.exe hosts the endpoint's runspacesshd → Subsystem powershell … pwsh -sshs
PlatformsWindows (Linux WinRM server support was removed long ago)Windows, Linux, macOS; PowerShell 6+ on both ends
Endpoints / JEA / disconnectYes: session configurations, JEA, Disconnect-PSSessionNo session configurations, no JEA, no disconnected sessions

Why: the endpoint decides which PowerShell you get

A session configuration (endpoint) is a named WinRM plug-in: which PowerShell version, who may connect (an ACL), which commands are visible, and which account runs it. On Windows, Enable-PSRemoting in Windows PowerShell registers microsoft.powershell; running it in pwsh registers PowerShell.7 and a version-specific PowerShell.7.6.x. When you omit -ConfigurationName, the client uses $PSSessionConfigurationName, which defaults to http://schemas.microsoft.com/powershell/Microsoft.PowerShell — Windows PowerShell 5.1, even from pwsh 7.6 (verified below). Your script block then runs under 5.1 rules: no ??, no -Parallel, different modules.

How: serialization — the core of this module

  1. The remote pipeline produces live .NET objects (a FileInfo, a Process …).
  2. The server serializes each one to CLIXML: the type names (<TN>), then properties to a depth (by default 1 level for most types, more for some, configured in types.ps1xml), each value as <S>, <I64>, <DT>…; ToString() is captured as a string.
  3. The client deserializes: known “primitive” types (string, numbers, bool, DateTime, TimeSpan, Guid, Version, IPAddress, byte[], …) are rehydrated into real objects; hashtables and arrays become real collections; everything else becomes a PSObject property bag whose type names are prefixed with Deserialized., with no methods except GetType() and ToString().
  4. PowerShell adds PSComputerName, RunspaceId and PSShowComputerName NoteProperties so you know where each object came from.

The same happens between processes on one machine: Start-Job runs a child pwsh and talks PSRP to it over pipes, so its output is deserialized too. Start-ThreadJob and ForEach-Object -Parallel stay in your process: no serialization, live objects (Modules 5–6).

When: what to do about it

SituationDo this
You need a method (.OpenText(), .Kill(), .Refresh())Call it inside the remote script block; return the result
You need a nested property ($f.Directory.Name)Select it remotely: Select-Object Name, @{n='Dir';e={$_.Directory.Name}}
You only need a few properties of a big objectSelect-Object remotely: less XML, faster, no depth surprises
Code relies on -is [System.IO.FileInfo]Test $_.pstypenames -contains 'Deserialized.System.IO.FileInfo' or return your own [pscustomobject] with a PSTypeName
The script block needs PowerShell 7 syntaxAlways pass -ConfigurationName PowerShell.7 on WinRM (or set $PSSessionConfigurationName); SSH always starts the pwsh in the Subsystem line
Common misconceptions① “Remoting returns the same objects I'd get locally” — you get a copy of the properties at the time of serialization. ② “pwsh 7 remoting means PowerShell 7 on the other side” — on WinRM the default endpoint is Windows PowerShell 5.1. ③ “5985 is plaintext HTTP, so passwords leak” — with Kerberos/NTLM the PSRP payload is encrypted at the message level; HTTPS adds server authentication and is required for Basic auth. ④ “Jobs are just background threads” — Start-Job is a separate process with full serialization; only ThreadJob and -Parallel are threads. ⑤ “SSH remoting is just ssh + pwsh -c” — it is full PSRP over the SSH channel: objects, streams, sessions; only endpoints/JEA/disconnect are missing.

Architecture: one PSRP client, two transports

Client: pwsh 7.6Invoke-Command / New-PSSessionPSRP client (runspace pool)serializer ⇄ deserializeradds PSComputerName -ComputerName WinRM serviceHTTP 5985 / HTTPS 5986Kerberos · NTLM · cert · CredSSPendpoint ACL check-ConfigurationName → plug-inTrustedHosts (client, NTLM) microsoft.powershell (default)wsmprovhost → Windows PowerShell 5.1 PowerShell.7 / PowerShell.7.6.xwsmprovhost + pwrshplugin → pwsh 7.6 -HostName sshd (OpenSSH)port 22 · keys / passworduser's own accountno endpoints, no JEAno disconnected sessions Subsystem powershellpwsh -sshs (server mode)any OS with pwsh 6+
Figure 1-1: the same PSRP messages ride on WinRM or SSH. On WinRM the endpoint you name (or the 5.1 default) decides which PowerShell runs your script block

Flow: a FileInfo crossing the wire

Remote: live objectSystem.IO.FileInfo23 methods.Directory = DirectoryInfo.Length = 600 (Int64).OpenText() ✓ serialize CLIXML on the wire<TN> type names<I64 N="Length">600<S N="Directory">C:\…\data<ToString> captured≈ 5.7 KB for one file deserialize Client: property bagDeserialized.System.IO.FileInfo2 methods (GetType, ToString).Directory = String.Length = 600 (Int64 ✓).OpenText() ✗ + NotePropertiesPSComputerNameRunspaceIdPSShowComputerName Same path for Start-Job (child process over pipes) — not for Start-ThreadJob or ForEach-Object -Parallel (same process, live objects)
Figure 1-2: numbers in this figure are from this lesson's real runs on 7.6.10 (servers.csv, 600 bytes)

Core animation: a FileInfo crossing the wire

Pick a boundary and step through what happens to the object. Logs are real outputs from 7.6.10.

Ready.
Real mechanism behind the animation The serializer walks each object's adapted properties up to the serialization depth (types can raise it with SerializationDepth in types.ps1xml), writes CLIXML, and the deserializer maps a fixed list of known types back to real .NET types. Everything else becomes a PSObject whose pstypenames start with Deserialized.. Formatting files contain views for many deserialized types, which is why a remote Get-Process still looks like a process table.

Command table

CommandPurposeNotes
Test-WSMan localhostIs a WinRM listener answering?Read-only; fails fast if WinRM is off
Get-PSSessionConfigurationList endpoints (pwsh lists PowerShell 7 ones)Needs elevation; read-only
Invoke-Command -ConfigurationName PowerShell.7Choose the endpointDefault: $PSSessionConfigurationName → 5.1
[System.Management.Automation.PSSerializer]::Serialize($o, $depth)Serialize like remoting does::Deserialize($xml) to rehydrate
Export-Clixml / Import-ClixmlThe same format, in a fileDefault depth 2; also how credentials are saved (DPAPI, Windows only — Module 7)
$o.pstypenamesType names, including Deserialized.*Get-Member shows the first one as TypeName
$o.PSComputerNameWhere a remote object came fromAlso RunspaceId, PSShowComputerName
# 1) Serialize a FileInfo the way remoting does, entirely locally
$file = Get-Item ~/pslab/data/servers.csv
$xml  = [System.Management.Automation.PSSerializer]::Serialize($file, 1)
$back = [System.Management.Automation.PSSerializer]::Deserialize($xml)
'{0,-12} {1}' -f 'original:', $file.GetType().FullName
'{0,-12} {1}' -f 'rehydrated:', ($back.pstypenames -join ' > ')
'{0,-12} {1} methods vs {2} methods' -f 'methods:', @($file | Get-Member -MemberType Method).Count, @($back | Get-Member -MemberType Method).Count
'Length survives: {0} ({1})' -f $back.Length, $back.Length.GetType().Name
'XML size: {0:N0} characters' -f $xml.Length
original:    System.IO.FileInfo
rehydrated:  Deserialized.System.IO.FileInfo > Deserialized.System.IO.FileSystemInfo > Deserialized.System.MarshalByRefObject > Deserialized.System.Object
methods:     23 methods vs 2 methods
Length survives: 600 (Int64)
XML size: 5,685 characters
# 2) A job is a second process: its output is deserialized too
$job = Start-Job -WorkingDirectory ~/pslab { Get-Item ./data/servers.csv }
$r = $job | Receive-Job -Wait -AutoRemoveJob
$r.pstypenames[0]
try { $r.OpenText() } catch { "OpenText(): $($_.Exception.Message)" }
$r | Get-Member -MemberType Method | Select-Object -ExpandProperty Name
"$r"          # ToString() was captured as a string before serialization
Deserialized.System.IO.FileInfo
OpenText(): Method invocation failed because [Deserialized.System.IO.FileInfo] does not contain a method named 'OpenText'.
GetType
ToString
C:\Users\labadmin\pslab\data\servers.csv
# 3) Real WinRM loopback: which endpoint answers, and what comes back?
Invoke-Command -ComputerName localhost { "$($PSVersionTable.PSEdition) $($PSVersionTable.PSVersion)" }
Invoke-Command -ComputerName localhost -ConfigurationName PowerShell.7 { "$($PSVersionTable.PSEdition) $($PSVersionTable.PSVersion)" }
$p = Invoke-Command -ComputerName localhost -ConfigurationName PowerShell.7 { Get-Process -Id $PID }
$p.pstypenames[0]
$p | Select-Object Name, PSComputerName, RunspaceId
Desktop 5.1.26100.10068
Core 7.6.10
Deserialized.System.Diagnostics.Process

Name        PSComputerName RunspaceId
----        -------------- ----------
wsmprovhost localhost      b2fa3ca6-7679-4c33-9564-9dbe737756c5

How to verify: the first line is the proof that the default endpoint is Windows PowerShell 5.1; the process name wsmprovhost shows that the PowerShell 7 endpoint is hosted by the WinRM provider host process, not by a pwsh.exe. Common mistake: testing a script block in pwsh locally, then running it remotely without -ConfigurationName and getting 5.1 parser errors — Invoke-Command -ComputerName localhost { 1 ?? 2 } returns Unexpected token '??' in expression or statement. (verified on the lab machine). Production use: set $PSSessionConfigurationName = 'PowerShell.7' at the top of fleet scripts, or pass it explicitly everywhere.

# 4) Which types survive the trip with full fidelity?
$sample = [ordered]@{
    Int       = 42
    String    = 'web-01'
    DateTime  = [datetime]'2026-11-24T10:00:00'
    TimeSpan  = [timespan]::FromSeconds(90)
    Guid      = [guid]'0f8fad5b-d9cb-469f-a165-70867728950e'
    Version   = [version]'7.6.10'
    IPAddress = [ipaddress]'10.10.1.21'
    Hashtable = @{ a = 1 }
    PSCustom  = [pscustomobject]@{ Name = 'web-01' }
    FileInfo  = Get-Item ~/pslab/data/servers.csv
}
foreach ($k in $sample.Keys) {
    $copy = [System.Management.Automation.PSSerializer]::Deserialize(
        [System.Management.Automation.PSSerializer]::Serialize($sample[$k]))
    [pscustomobject]@{ Value = $k; RealType = $copy.GetType().Name; TypeName = $copy.pstypenames[0] }
}
Value     RealType       TypeName
-----     --------       --------
Int       Int32          System.Int32
String    String         System.String
DateTime  DateTime       System.DateTime
TimeSpan  TimeSpan       System.TimeSpan
Guid      Guid           System.Guid
Version   Version        System.Version
IPAddress IPAddress      System.Net.IPAddress
Hashtable Hashtable      Deserialized.System.Collections.Hashtable
PSCustom  PSCustomObject Deserialized.System.Management.Automation.PSCustomObject
FileInfo  PSObject       Deserialized.System.IO.FileInfo

Read the two columns separately: a Hashtable comes back as a real Hashtable (usable as usual) but tagged Deserialized.…; a FileInfo comes back as a plain PSObject. Your own [pscustomobject] results lose nothing that matters — which is why OpsKit returns custom objects.

# 5) What actually travels: CLIXML
[pscustomobject]@{ Name = 'web-01'; Port = 8080; Up = $true; Checked = [datetime]'2026-11-24T10:00:00Z' } |
    Export-Clixml ~/pslab/tmp/server.clixml
Get-Content ~/pslab/tmp/server.clixml
$back = Import-Clixml ~/pslab/tmp/server.clixml
"$($back.pstypenames[0]) | Port is $($back.Port.GetType().Name) | Up is $($back.Up.GetType().Name)"
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Management.Automation.PSCustomObject</T>
      <T>System.Object</T>
    </TN>
    <MS>
      <S N="Name">web-01</S>
      <I32 N="Port">8080</I32>
      <B N="Up">true</B>
      <DT N="Checked">2026-11-24T05:00:00-05:00</DT>
    </MS>
  </Obj>
</Objs>
Deserialized.System.Management.Automation.PSCustomObject | Port is Int32 | Up is Boolean

Goal: See deserialization with your own eyes — locally, through a process job and (if available) through WinRM loopback — and find the one property that silently changes type. Environment: any PowerShell 7.6 (step 3 needs Windows with WinRM enabled). Cost: none.

Serialize locally: run command block 1 from the Commands tab and confirm the type name chain and the method count (23 → 2).
Through a job: run block 2. Then compare a nested property locally and from the job:
# Depth: below the serialization depth, .NET objects are flattened to strings
$f = Start-Job -WorkingDirectory ~/pslab { Get-Item ./data/servers.csv } | Receive-Job -Wait -AutoRemoveJob
"Directory      : $($f.Directory.GetType().Name) = '$($f.Directory)'"
"Directory.Name : '$($f.Directory.Name)'"
$local = Get-Item ~/pslab/data/servers.csv
"local          : $($local.Directory.GetType().Name), Name = '$($local.Directory.Name)'"
Directory      : String = 'C:\Users\labadmin\pslab\data'
Directory.Name : ''
local          : DirectoryInfo, Name = 'data'

No error, just an empty string: .Name on a [string] does not exist and PowerShell returns $null (outside strict mode — Lesson 5). This is the most common silent remoting bug.

Through WinRM loopback (only if Test-WSMan localhost works): run block 3. Note which edition answers without -ConfigurationName.
Fix the depth bug at the source: return exactly what you need, computed remotely.
Start-Job -WorkingDirectory ~/pslab {
    Get-Item ./data/servers.csv | Select-Object Name, Length, @{ n = 'Folder'; e = { $_.Directory.Name } }
} | Receive-Job -Wait -AutoRemoveJob | Select-Object Name, Length, Folder
Name        Length Folder
----        ------ ------
servers.csv    600 data
Cleanup: Remove-Item -LiteralPath ~/pslab/tmp/server.clixml -ErrorAction Ignore; Get-Job | Remove-Job -Force

Case 1: a fleet script “worked in testing” and failed on every server

Problem: A disk-report script using $size ?? 0 and ForEach-Object -Parallel ran fine in an engineer's pwsh 7 session; via Invoke-Command -ComputerName (Get-Content servers.txt) every server returned a parser error. Root cause: no -ConfigurationName, so each server ran it in the default microsoft.powershell endpoint — Windows PowerShell 5.1, which knows neither ?? nor -Parallel. Fix: register PowerShell 7 endpoints on the servers (change-managed), pass -ConfigurationName PowerShell.7, and add #Requires -Version 7.4 logic inside the script block (if ($PSVersionTable.PSVersion.Major -lt 7) { throw … }) so a wrong endpoint fails loudly.

Case 2: “Kill the hung process on all web servers” did nothing

Problem: $p = Invoke-Command -ComputerName $web { Get-Process w3wp }; $p | ForEach-Object { $_.Kill() } threw “does not contain a method named 'Kill'”. A colleague then tried $p | Stop-Process, which tried to stop processes with the same IDs on the admin workstation. Root cause: deserialized objects have no methods and are not bound to their machine. Fix: act remotely: Invoke-Command -ComputerName $web { Get-Process w3wp | Where-Object CPU -gt 600 | Stop-Process -WhatIf }, review, then run without -WhatIf.

Case 3: a report's “Folder” column was empty for every row

Problem: An audit collected files from 40 servers with Invoke-Command { Get-ChildItem D:\Shares -Recurse } and built the report locally with $_.Directory.Name; the column was blank and nobody noticed for weeks. Root cause: Directory is below the serialization depth and arrives as a string. Fix: compute every column remotely with Select-Object and calculated properties; add Set-StrictMode -Version Latest in the reporting code so a missing property throws instead of returning $null.

Common errors and fixes

Method invocation failed because [Deserialized.System.…] does not contain a method named '…'

Cause: calling a method on an object that came back from remoting or Start-Job.

$o.pstypenames[0]      # starts with Deserialized.

Fix: call the method inside the remote script block, or use ThreadJob/-Parallel if you just need concurrency on the local machine.

Remote script block fails with “Unexpected token” on syntax that works locally

Cause: you reached the default 5.1 endpoint.

Invoke-Command -ComputerName srv1 { $PSVersionTable.PSVersion }

Fix: -ConfigurationName PowerShell.7; if it does not exist on the server, the server needs PowerShell 7 and Enable-PSRemoting run from pwsh (an admin change).

Connecting to remote server … failed: The client cannot connect to the destination specified in the request (WinRM)

Cause: no WinRM listener (service stopped or never enabled), firewall, or wrong port.

Test-WSMan srv1
Test-NetConnection srv1 -Port 5985

Fix: on the server, an administrator runs Enable-PSRemoting (or Group Policy); never as a side effect of a script.

A property is empty or a string although it was an object locally

Cause: serialization depth flattened it.

Fix: select the nested value remotely; do not raise depth globally — it makes every result bigger.

Command-line exercises
1. Write one line that tells you whether an object $x came back deserialized.
$x.pstypenames[0] -like 'Deserialized.*'
2. Serialize Get-Date with PSSerializer and show the rehydrated type.
[System.Management.Automation.PSSerializer]::Deserialize(
  [System.Management.Automation.PSSerializer]::Serialize((Get-Date))).GetType().FullName   # System.DateTime
Scenario analysis
A teammate wants to “return the whole service object so the caller can call .Stop() later if needed.” What do you tell them?

The caller will receive a Deserialized.System.ServiceProcess.ServiceController: no Stop(), not connected to the server, and a snapshot of the state at serialization time. Design the remote side to act (with -WhatIf support) and to report small custom objects: name, status before, status after, computer. The caller decides by running a second remote command, not by calling methods on copies.

Verified teaching videos

▶
PowerShell Master Class - PowerShell Remoting — John Savill's Technical Training
English · WinRM remoting, sessions, deserialized objects (recorded before 7.6; endpoint names may differ)

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–20s
Visual: a laptop and a server; two pipes between them labelled WinRM 5985 and SSH 22.
Narration: one protocol, two transports. WinRM for Windows fleets, SSH for everything.
Shot 2 · 20–45s
Visual: the WinRM pipe forks into two doors: “microsoft.powershell 5.1 (default)” in red and “PowerShell.7” in green.
Narration: the endpoint decides which PowerShell runs your code. The default is 5.1.
Shot 3 · 45–75s
Visual: a FileInfo object with 23 method icons enters an XML shredder and comes out as a flat card with 2 icons; the Directory property turns into a plain text label.
Narration: objects travel as XML. Properties survive, methods don't, nested objects become strings.
Shot 4 · 75–90s
Visual: “Select what you need, remotely” stamped over the script block.
Narration: compute remotely, return small custom objects.
or score ≥ 70% on the Quiz

Module 2 · Invoke-Command: fan-out, -ThrottleLimit, $using: and per-computer errors

06:00 – 13:00 · One command, many computers: connections are opened in parallel up to the throttle limit, every result is tagged with PSComputerName, and one unreachable server must not cost you the results of all the others
7 minWinRM loopback (real)★★★★★
Learning objectives
  • Run a script block on many computers with Invoke-Command -ComputerName $list and explain how -ThrottleLimit (default 32) bounds concurrent connections.
  • Pass local values with $using: (or -ArgumentList + param()) and explain why a plain $delay is empty remotely.
  • Collect failures per computer with -ErrorAction SilentlyContinue -ErrorVariable, and show why -ErrorAction Stop on a fan-out throws away the good results.
  • Use PSComputerName to attribute results, -HideComputerName for display, and -AsJob to fan out in the background.
Prerequisites: Module 1; Lesson 5 (error records, -ErrorVariable). Importance:★★★★★ (the day-to-day remoting command)

What: one script block, N runspaces

Invoke-Command -ComputerName a,b,c { … } opens a temporary session to each computer (up to -ThrottleLimit at a time), sends the script block, streams results back as they arrive, and closes each session afterwards. Output order is completion order, not the order of -ComputerName; every object carries PSComputerName. The Bash equivalent is a loop of ssh host cmd & plus wait, or xargs -P / parallel-ssh — but here you get objects with an origin tag and structured errors.

ParameterMeaningDefault / note
-ComputerNameTargets (names, FQDNs, IPs)IPs and non-domain names need NTLM + TrustedHosts or HTTPS
-ThrottleLimitMax concurrent connections for this command32
-ConfigurationNameEndpointUse PowerShell.7 (Module 1)
-ArgumentListValues for the block's param()Positional; serialized
$using:nameRead a local variable inside the blockRead-only copy, serialized (except with ThreadJob/-Parallel, where it is a reference — Module 6)
-AsJobReturn a parent job with one child per computerCollect with Receive-Job
-HideComputerNameSets PSShowComputerName = $falseDisplay only; PSComputerName is still there
-FilePathSend a local .ps1 file's contentThe file is read locally; it runs remotely

Why: errors are per computer

Connection failures (name not resolved, access denied, WinRM down) are non-terminating errors, one per failed computer, with TargetObject = the computer name and FullyQualifiedErrorId such as ComputerNotFound,PSSessionStateBroken. Errors from inside the script block come back the same way, tagged with PSComputerName. That is what you want: 199 servers succeed, 1 fails, you get 199 results and 1 error record. -ErrorAction Stop breaks this: the first error becomes terminating and the whole command — including the results already received — is lost to your variable (verified below).

How: the safe fan-out pattern

$results = Invoke-Command -ComputerName $servers -ConfigurationName PowerShell.7 -ThrottleLimit 16 `
    -ErrorAction SilentlyContinue -ErrorVariable fanErr -ScriptBlock { … }
$failed = $fanErr | ForEach-Object { [pscustomobject]@{ Computer = $_.TargetObject; Error = $_.FullyQualifiedErrorId } }
$missing = $servers | Where-Object { $_ -notin $results.PSComputerName }   # cross-check

When: choosing the throttle

WorkloadThrottleWhy
Short, read-only queries32–64Mostly network latency; admin workstation is the bottleneck
Heavy remote work (patch scan, log search)8–16Each connection costs CPU/RAM on the client (one runspace each) and the targets
Changes (restart services, deploy)Waves: 1 canary, then 10%, then the restLimits the blast radius; check results between waves
Common misconceptions① “Results come back in the order of -ComputerName” — completion order; sort by PSComputerName. ② “-ErrorAction Stop makes fan-outs safer” — it discards everything on the first unreachable host. ③ “Local variables are visible remotely” — only via $using: or -ArgumentList. ④ “-HideComputerName removes PSComputerName” — it only hides the column. ⑤ “ThrottleLimit is global” — it applies to that one command; two parallel scripts each use their own.

Fan-out with a throttle of 2

Invoke-Command-ComputerName 6 hosts-ThrottleLimit 2$using:delay = 2 time → srv1 (2 s) srv2 (2 s) srv3 srv4 srv5 srv6 ✗ Output stream (completion order): objects + PSComputerNamesrv2, srv1, srv4, srv3, srv5 … Error stream: one ErrorRecord per failed computerTargetObject = srv6 · ComputerNotFound,PSSessionStateBroken ≈ 3 waves6 hosts / 2 slotsmeasured: 8.6 svs 3.3 s with 6
Figure 2-1: the throttle creates waves; results and errors stream back independently. Measured on loopback: 6 × 2 s took 3.3 s with ThrottleLimit 6 and 8.6 s with ThrottleLimit 2 (connection set-up adds ≈1 s per wave)

Where values come from

Local runspace$delay = 2$servers = …functions, modules, $PWD $using:delay → serialized value 2 -ArgumentList 2 → param($d) Remote runspace (fresh)$delay → $null (not defined)$using:delay → 2no local functions or modulesits own $HOME, $PWD, $env:
Figure 2-2: the script block is sent as text; only $using: values and arguments travel with it

Fan-out simulator

Each scenario follows one Invoke-Command call. Logs are real outputs from the loopback runs in the Commands tab.

Ready.
Real mechanism behind the animation Invoke-Command creates a remote runspace per computer through a throttle manager, starts the same pipeline in each, and merges their output and error streams into yours as messages arrive. Connection failures surface as error records with the session state Broken, hence …,PSSessionStateBroken in the error id.

Command table

CommandPurposeNotes
Invoke-Command -ComputerName $list { … }Fan outTemporary sessions
… -ThrottleLimit 16Bound concurrencyDefault 32
… -ErrorAction SilentlyContinue -ErrorVariable eKeep going, collect failures$e.TargetObject = computer
{ … $using:x … }Use a local valueRead-only; cannot assign $using:x = …
-ArgumentList a, b + param($p1, $p2)Explicit parametersGood for -FilePath scripts
-AsJobBackground fan-outParent RemoteJob + child per host
Sort-Object PSComputerNameStable orderResults arrive in completion order
# Fan out to four "computers": two work, two fail for different reasons
$targets = 'localhost', $env:COMPUTERNAME, '127.0.0.1', 'nohost-01'
$res = Invoke-Command -ComputerName $targets -ConfigurationName PowerShell.7 -ScriptBlock {
    [pscustomobject]@{ Pid = $PID; Edition = $PSVersionTable.PSEdition }
} -ErrorAction SilentlyContinue -ErrorVariable fanErr
$res | Sort-Object PSComputerName | Format-Table PSComputerName, Pid, Edition
"{0} results, {1} errors" -f @($res).Count, $fanErr.Count
$fanErr | ForEach-Object {
    [pscustomobject]@{
        Target = $_.TargetObject.ToString()
        Id     = $_.FullyQualifiedErrorId
        Reason = $_.Exception.Message.Substring(0, 70) + '…'
    }
} | Format-List
PSComputerName   Pid Edition
--------------   --- -------
127.0.0.1      42560 Core
LAB01         11168 Core
localhost       1632 Core

3 results, 1 errors

Target : nohost-01
Id     : ComputerNotFound,PSSessionStateBroken
Reason : Connecting to remote server nohost-01 failed with the following error …

How to verify: three different PIDs = three separate wsmprovhost processes, one per connection. Honest note: 127.0.0.1 only worked because this lab machine has TrustedHosts = * (read with (Get-Item WSMan:\localhost\Client\TrustedHosts).Value). On a default machine an IP address target fails with an error telling you to use HTTPS or add the destination to TrustedHosts — the plan was to show that failure, and the machine's configuration turned it into a success. TrustedHosts = * disables server authentication for NTLM to every host: acceptable on an isolated lab, never in production. The full message for nohost-01 is “…The WinRM client cannot process the request because the server name cannot be resolved.”

# $using: and -ThrottleLimit, measured on loopback (six connections to the same machine)
$six = @('localhost') * 6
$delay = 2
foreach ($limit in 6, 2) {
    $t = Measure-Command {
        $r = Invoke-Command -ComputerName $six -ConfigurationName PowerShell.7 -ThrottleLimit $limit -ScriptBlock {
            Start-Sleep -Seconds $using:delay
            $PID
        }
    }
    '-ThrottleLimit {0}: {1} results from {2} processes in {3:N1} s' -f $limit, $r.Count, @($r | Sort-Object -Unique).Count, $t.TotalSeconds
}
# Without $using: the remote side has its own (empty) $delay
Invoke-Command -ComputerName localhost -ConfigurationName PowerShell.7 { "remote sees delay = '$delay'" }
# -AsJob: one parent job, one child job per computer
$j = Invoke-Command -ComputerName localhost, $env:COMPUTERNAME -ConfigurationName PowerShell.7 -AsJob { $env:COMPUTERNAME }
$j | Format-Table Id, Name, PSJobTypeName, State, HasMoreData, Location
$j.ChildJobs | Format-Table Id, Location, State
$j | Wait-Job | Receive-Job | ForEach-Object { "$_ (PSComputerName=$($_.PSComputerName))" }
$j | Remove-Job
-ThrottleLimit 6: 6 results from 6 processes in 3.3 s
-ThrottleLimit 2: 6 results from 6 processes in 8.6 s
remote sees delay = ''

Id Name PSJobTypeName State   HasMoreData Location
-- ---- ------------- -----   ----------- --------
 4 Job4 RemoteJob     Running        True localhost,LAB01


Id Location  State
-- --------  -----
 5 localhost NotStarted
 6 LAB01    NotStarted

LAB01 (PSComputerName=localhost)
LAB01 (PSComputerName=LAB01)

Each connection costs about a second here (session creation, authentication, loading the endpoint) on top of the 2 s of work, which is why ThrottleLimit 6 took 3.3 s, not 2 s. Note that both results say LAB01 — it is the same machine — but PSComputerName records the name you used.

# -ErrorAction Stop on a fan-out: one bad name throws away the good results
$r = 'nothing assigned'
try {
    $r = Invoke-Command -ComputerName localhost, nohost-01 -ConfigurationName PowerShell.7 { $env:COMPUTERNAME } -ErrorAction Stop
} catch { "caught: $($_.FullyQualifiedErrorId)" }
"r = $r"
# Better: collect errors per computer and keep going
$r = Invoke-Command -ComputerName localhost, nohost-01 -ConfigurationName PowerShell.7 { $env:COMPUTERNAME } -ErrorAction SilentlyContinue -ErrorVariable bad
"r = $r (from $($r.PSComputerName)); failed: $($bad.TargetObject -join ', ')"
caught: ComputerNotFound,PSSessionStateBroken
r = nothing assigned
r = LAB01 (from localhost); failed: nohost-01
# -HideComputerName only changes the display
$a = Invoke-Command -ComputerName localhost -ConfigurationName PowerShell.7 { [pscustomobject]@{ Year = 2026 } }
$b = Invoke-Command -ComputerName localhost -ConfigurationName PowerShell.7 -HideComputerName { [pscustomobject]@{ Year = 2026 } }
"default : PSShowComputerName = $($a.PSShowComputerName)"
"hidden  : PSShowComputerName = $($b.PSShowComputerName), PSComputerName = $($b.PSComputerName)"
$b
default : PSShowComputerName = True
hidden  : PSShowComputerName = False, PSComputerName = localhost

Year RunspaceId
---- ----------
2026 adfea9be-9fae-4398-b465-0664edd410b8

Common mistake: writing @($r).Count to check whether anything came back after a failed assignment — @($null).Count is 1 (this bit the author while preparing the demo; the sentinel string above is the reliable check). Production use: always pair -ErrorVariable with a reconciliation step ($servers | Where-Object { $_ -notin $results.PSComputerName }), and write failures to the structured log from Lesson 5.

Goal: Build a fan-out that reports successes and failures per computer and measure the throttle. Environment: Windows with WinRM loopback working (otherwise read the outputs). Cost: none; no configuration changes.

Fan out with a deliberate failure: run the first command block. Expect 3 results + 1 error, or — on a default machine — 2 results + 2 errors (the 127.0.0.1 TrustedHosts error).
Turn errors into a report:
$servers = 'localhost', 'nohost-01', 'nohost-02'
$ok = Invoke-Command -ComputerName $servers -ConfigurationName PowerShell.7 { $PSVersionTable.PSVersion.ToString() } `
        -ErrorAction SilentlyContinue -ErrorVariable fanErr
$report = foreach ($s in $servers) {
    $hit = $ok | Where-Object PSComputerName -eq $s
    [pscustomobject]@{ Computer = $s; Ok = [bool]$hit; Version = "$hit"
                       Error = ($fanErr | Where-Object { "$($_.TargetObject)" -eq $s }).FullyQualifiedErrorId }
}
$report | Format-Table
Computer     Ok Version Error
--------     -- ------- -----
localhost  True 7.6.10
nohost-01 False         ComputerNotFound,PSSessionStateBroken
nohost-02 False         ComputerNotFound,PSSessionStateBroken
Measure the throttle: run the second command block. Try -ThrottleLimit 1 as well and predict the time first (≈ 6 × (2 s + connection) ≈ 17–18 s).
Prove the $using: copy is one-way: $n = 1; Invoke-Command -ComputerName localhost -ConfigurationName PowerShell.7 { $x = $using:n; $x++; $x }; $n → remote prints 2, local $n is still 1 (verified: output 2 then 1).
Cleanup: Get-Job | Remove-Job -Force; Get-PSSession | Remove-PSSession (temporary sessions close by themselves).

Case 1: the patch-status report silently had 180 of 200 servers

Problem: A weekly compliance report piped Invoke-Command -ComputerName $all { Get-HotFix } into Export-Csv. Twenty servers had a broken WinRM listener; the red error text scrolled by in a scheduled task nobody watched, and the CSV looked complete. Root cause: per-computer errors were neither collected nor reconciled. Fix: -ErrorVariable + a “missing hosts” check, a separate failed.csv, and a non-zero exit code when anything is missing (Lesson 5's exit-code contract).

Case 2: a restart script stopped half-way and nobody knew which half

Problem: Invoke-Command -ComputerName $web { Restart-Service W3SVC } -ErrorAction Stop inside try/catch; one decommissioned name in the list threw, the catch logged “restart failed”, and the team re-ran it on all servers during business hours. Root cause: -ErrorAction Stop on a fan-out loses the results (and the information) for hosts that did succeed. Fix: collect per-computer results, restart in waves (-ThrottleLimit 5, canary first), and log each host's before/after state.

Case 3: the admin workstation ran out of memory

Problem: Invoke-Command -ComputerName (2,000 names) -ThrottleLimit 500 { Get-WinEvent -LogName Security -MaxEvents 5000 } consumed 14 GB on the client. Root cause: 500 concurrent runspaces, each deserializing thousands of event objects with all properties. Fix: filter and Select-Object remotely (filter left, Lesson 1), lower the throttle to 32–64, and stream to disk (| Export-Csv -Append) instead of collecting into a variable.

Common errors and fixes

The WinRM client cannot process the request. Default authentication may be used with an IP address under the following conditions: the transport is HTTPS or the destination is in the TrustedHosts list…

Cause: an IP address or non-domain name means no Kerberos; NTLM requires TrustedHosts or HTTPS.

(Get-Item WSMan:\localhost\Client\TrustedHosts).Value   # read-only

Fix: use the DNS/FQDN name in a domain; otherwise HTTPS (5986) with a certificate, or SSH remoting. Adding entries to TrustedHosts is an admin change — never * in production.

Connecting to remote server srv1 failed … Access is denied.

Cause: your account is not in the endpoint's ACL (local Administrators or Remote Management Users by default), or UAC remote restrictions for local accounts.

Fix: use a domain account with rights, or JEA (Module 7) for delegated, limited access.

The variable is empty inside the script block

Cause: no $using:.

Invoke-Command -ComputerName srv1 { Get-Service -Name $using:svc }
A Using variable cannot be retrieved…

Cause: $using: in a script block that is not run remotely or as a job (for example called with & locally).

Fix: use -ArgumentList/param() if the block is used in both contexts.

Command-line exercises
1. Run Get-Date on three computers, at most two at a time, and print “computer: date” lines sorted by computer.
Invoke-Command -ComputerName a, b, c -ThrottleLimit 2 -ConfigurationName PowerShell.7 { Get-Date } |
  Sort-Object PSComputerName | ForEach-Object { "$($_.PSComputerName): $_" }
2. Pass a local array of service names to the remote side two ways.
$names = 'WinRM', 'W32Time'
Invoke-Command -ComputerName srv1 { Get-Service -Name $using:names }
Invoke-Command -ComputerName srv1 -ArgumentList (,$names) { param($n) Get-Service -Name $n }

The unary comma keeps the array as one argument instead of spreading it across parameters.

Scenario analysis
You must restart a service on 300 servers tonight. Design the Invoke-Command call(s).

Wave 1: one canary with -WhatIf, then for real; check its result object. Wave 2: 10% with -ThrottleLimit 10. Wave 3: the rest with -ThrottleLimit 32. Each call: -ConfigurationName PowerShell.7, -ErrorAction SilentlyContinue -ErrorVariable, a script block that returns [pscustomobject]@{ Before; After; Duration }; reconcile missing hosts after each wave and stop if the failure rate exceeds a threshold. Log everything as JSON (Lesson 5).

Verified teaching videos

▶
PowerShell Master Class - PowerShell Remoting — John Savill's Technical Training
English · Invoke-Command against multiple machines, sessions

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–25s
Visual: one script block copied to six servers, two lanes at a time (throttle), results flying back tagged with names.
Narration: fan-out is parallel, bounded by the throttle, tagged by PSComputerName.
Shot 2 · 25–55s
Visual: one server turns red; with -ErrorVariable the five green results stay in the basket; with -ErrorAction Stop the basket is tipped over.
Narration: collect errors per computer. Don't let one bad host cost you the rest.
Shot 3 · 55–90s
Visual: a variable $delay on the laptop, an empty box on the server; then a “$using:” arrow carries the value.
Narration: the remote runspace is empty. Bring values with $using: or arguments.
or score ≥ 70% on the Quiz

Module 3 · Sessions: New-PSSession, Enter-PSSession, reuse and file copy

13:00 – 21:00 · A persistent session keeps one remote runspace alive: no reconnect cost, state survives between calls, files travel over the same channel, and on WinRM you can even disconnect and come back later
8 minWinRM loopback (real)★★★★☆
Learning objectives
  • Create, use and remove sessions (New-PSSession, Invoke-Command -Session, Remove-PSSession) and measure the saving: 10 calls in 287 ms instead of 6,727 ms on loopback.
  • Use state across calls (variables, imported modules, location) and know that it lives only as long as the session.
  • Work interactively with Enter-PSSession/Exit-PSSession and know what does not work there (interactive native programs, second hop).
  • Copy files with Copy-Item -ToSession/-FromSession; disconnect and collect results later with -InDisconnectedSession + Receive-PSSession (WinRM only); use implicit remoting with Import-PSSession.
Prerequisites: Modules 1–2. Importance:★★★★☆

What: temporary vs persistent sessions

Invoke-Command -ComputerNameNew-PSSession + -Session
ConnectionOpened and closed per commandOpened once, reused until Remove-PSSession (or idle timeout)
StateLost after each commandVariables, functions, imported modules, location persist
Cost per call (loopback, measured)≈ 670 ms≈ 29 ms
Good forOne-shot fan-outSeveral steps on the same machines; file copy; interactive work

Why: session objects and their states

A PSSession object (Id, Name, ComputerName, ConfigurationName, State, Availability) is your handle to a runspace on the server. States: Opened (usable), Disconnected (server keeps running it; WinRM only), Broken (network lost or server rebooted — recreate it), Closed (removed). Every open session holds a wsmprovhost process and counts against server quotas such as MaxShellsPerUser, so leaked sessions eventually block new connections.

How: the four session tools

  • Reuse: $s = New-PSSession -ComputerName $list -ConfigurationName PowerShell.7, then Invoke-Command -Session $s as often as needed (fan-out works on an array of sessions too, with -ThrottleLimit).
  • Interactive: Enter-PSSession $s changes the prompt to [srv1]: PS C:\>; every line runs remotely; Exit-PSSession returns. It is for humans, never for scripts.
  • Files: Copy-Item -ToSession $s / -FromSession $s stream file content over PSRP — no SMB share or admin share needed, works over SSH sessions too.
  • Disconnect (WinRM): Invoke-Command -InDisconnectedSession or Disconnect-PSSession; later, from any machine, Get-PSSession -ComputerName srv1 → Connect-PSSession / Receive-PSSession. The remote work keeps running while you are away.

When: implicit remoting

Import-PSSession $s -Module ActiveDirectory -Prefix Corp generates local proxy functions (Get-CorpADUser) that run on the server: you use a module that is not installed locally. Results are still deserialized. PowerShell 7's Windows PowerShell compatibility feature uses exactly this mechanism (a hidden local WinPSCompatSession) when you import a 5.1-only module.

Common misconceptions① “Enter-PSSession inside a script runs the rest of the script remotely” — it does not; the next script lines still run locally. Use Invoke-Command -Session. ② “Sessions close themselves” — persistent sessions stay until removed, the idle timeout (2 h by default) expires, or the client process exits. ③ “Copy-Item to a remote machine needs \\server\c$” — -ToSession uses the PSRP channel. ④ “Disconnected sessions work over SSH” — WinRM only. ⑤ “Implicit remoting returns live objects” — they are deserialized like any remote result.

Session lifecycle

New-PSSessionauth + endpoint OpenedInvoke-Command -SessionCopy-Item -ToSession Disconnect Connect Disconnectedwork continues on serverWinRM only · Receive-PSSession Brokennetwork / reboot → recreate ClosedRemove-PSSession Each Opened/Disconnected session = one wsmprovhost process on the server,counted against MaxShellsPerUser / idle timeout (default 2 hours)
Figure 3-1: always end in Closed; Broken sessions cannot be repaired, only replaced

Session lifecycle simulator

Ready.
Real mechanism behind the animation New-PSSession performs the expensive part once — TCP/HTTP connection, authentication, creating the shell on the server, loading the endpoint's runspace. Invoke-Command -Session then only sends a pipeline message to the existing runspace, which is why the per-call cost drops by more than 20×.

Command table

CommandPurposeNotes
New-PSSession -ComputerName a,b -ConfigurationName PowerShell.7 -Name opsOpen sessionsReturns one PSSession per computer
Invoke-Command -Session $s { … }Run in existing sessionsFan-out across an array of sessions
Enter-PSSession $s / Exit-PSSessionInteractive remote promptHumans only
Copy-Item -ToSession $s / -FromSession $sFile transfer over PSRPPaths on the remote side are remote paths
Invoke-Command -InDisconnectedSession -SessionName xStart work and disconnect at onceWinRM only
Get-PSSession -ComputerName srvFind your sessions on a serverIncluding ones from other clients
Connect-PSSession / Receive-PSSessionReconnect / collect output-OutTarget Job to get a job
Import-PSSession $s -CommandName X -Prefix PImplicit remotingCreates a temporary local module
Get-PSSession | Remove-PSSessionClean upPut it in finally
# 1) Ten calls: new connection each time vs one reused session
$cn = @{ ComputerName = 'localhost'; ConfigurationName = 'PowerShell.7' }
$fresh = Measure-Command { 1..10 | ForEach-Object { Invoke-Command @cn { $PID } } }
$s = New-PSSession @cn -Name ops
$reuse = Measure-Command { 1..10 | ForEach-Object { Invoke-Command -Session $s { $PID } } }
'fresh connection x10: {0,6:N0} ms' -f $fresh.TotalMilliseconds
'reused session  x10: {0,6:N0} ms' -f $reuse.TotalMilliseconds

# 2) A session keeps state between calls
Invoke-Command -Session $s { $counter = 41; Set-Location $env:TEMP }
Invoke-Command -Session $s { $counter += 1; "counter=$counter location=$((Get-Location).Path -replace '.*\\', '…\')" }
$s | Format-Table Id, Name, ComputerName, ComputerType, State, ConfigurationName, Availability

# 3) Copy files over the session (no SMB share needed)
# (loopback lab: the "remote" folder is ~/pslab/tmp/remote; on a real server use e.g. C:\Temp)
$remoteDir = Invoke-Command -Session $s { (New-Item -ItemType Directory -Path '~/pslab/tmp/remote' -Force).FullName }
Copy-Item -Path ~/pslab/data/servers.csv -Destination $remoteDir -ToSession $s
Invoke-Command -Session $s { Get-ChildItem $using:remoteDir | Select-Object Name, Length }  | Format-Table Name, Length, PSComputerName
Copy-Item -Path "$remoteDir/servers.csv" -Destination ~/pslab/tmp/servers.fromsession.csv -FromSession $s
(Get-FileHash ~/pslab/data/servers.csv).Hash -eq (Get-FileHash ~/pslab/tmp/servers.fromsession.csv).Hash
Invoke-Command -Session $s { Remove-Item -LiteralPath $using:remoteDir -Recurse -Force }
Remove-PSSession $s
Get-PSSession | Measure-Object | Select-Object -ExpandProperty Count
fresh connection x10:  6,727 ms
reused session  x10:    287 ms
counter=42 location=…\Temp

Id Name ComputerName  ComputerType  State ConfigurationName Availability
-- ---- ------------  ------------  ----- ----------------- ------------
21 ops  localhost    RemoteMachine Opened PowerShell.7         Available


Name        Length PSComputerName
----        ------ --------------
servers.csv    600 localhost

True
0

How to verify: the hash comparison returns True, and Get-PSSession counts 0 at the end. Common mistake: passing a local path to the remote side or the other way round — in -ToSession the -Path is local and -Destination is remote; in -FromSession it is reversed. Production use: open sessions in try, remove them in finally; with many servers use New-PSSession -ThrottleLimit and handle the ones that failed to open exactly like Module 2.

# Disconnected sessions (WinRM only): start work, walk away, collect later
$d = Invoke-Command -ComputerName localhost -ConfigurationName PowerShell.7 -InDisconnectedSession -SessionName longrun {
    Start-Sleep -Seconds 3
    "finished on $env:COMPUTERNAME in process $PID"
}
$d | Format-Table Id, Name, State, Availability
Get-PSSession -ComputerName localhost -Name longrun | Format-Table Id, Name, State, Availability
Start-Sleep -Seconds 4
Receive-PSSession -ComputerName localhost -Name longrun -ConfigurationName PowerShell.7 -OutTarget Job | Receive-Job -Wait
Get-PSSession -ComputerName localhost -Name longrun | Remove-PSSession

# Implicit remoting: remote commands become local proxy functions
$s3 = New-PSSession -ComputerName localhost -ConfigurationName PowerShell.7
$null = Import-PSSession -Session $s3 -CommandName Get-Process -Prefix Lab -AllowClobber
Get-Command Get-LabProcess | Format-Table CommandType, Name, Source -AutoSize
@(Get-LabProcess -Name wsmprovhost)[0].pstypenames[0]
Remove-PSSession $s3
Id Name           State Availability
-- ----           ----- ------------
 2 longrun Disconnected         None


Id Name           State Availability
-- ----           ----- ------------
 2 longrun Disconnected         None

finished on LAB01 in process 48048

CommandType Name           Source
----------- ----           ------
   Function Get-LabProcess tmp_y1k0glle.mcy

Deserialized.System.Diagnostics.Process

The first version of this demo used Receive-PSSession without -OutTarget and got back a still-Running job object instead of the output; -OutTarget Job | Receive-Job -Wait is the reliable form in a script. The proxy module name (tmp_…) is random per import.

Enter-PSSession (interactive)

Enter-PSSession -ComputerName localhost -ConfigurationName PowerShell.7
$PSVersionTable.PSVersion.ToString(); $env:COMPUTERNAME
Exit-PSSession
[localhost]: PS C:\Users\labadmin\Documents> $PSVersionTable.PSVersion.ToString(); $env:COMPUTERNAME
7.6.10
LAB01
[localhost]: PS C:\Users\labadmin\Documents> Exit-PSSession
PS C:\Users\labadmin>

Goal: Use one session for a multi-step task: import a module remotely, run two commands, copy a result file back, and clean up even if a step fails. Environment: WinRM loopback (or any session from Module 4). Cost: none.

Measure: run block 1 of the Commands tab and note your fresh vs reused numbers.
Multi-step with guaranteed cleanup:
$s = New-PSSession -ComputerName localhost -ConfigurationName PowerShell.7
try {
    Invoke-Command -Session $s { Import-Module Microsoft.PowerShell.Utility; $start = Get-Date }
    Invoke-Command -Session $s {
        Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 3 Name, @{ n = 'MB'; e = { [int]($_.WorkingSet64 / 1MB) } } |
            ConvertTo-Json | Set-Content -LiteralPath (Join-Path ([IO.Path]::GetTempPath()) 'top3.json')
        "took $(((Get-Date) - $start).TotalMilliseconds) ms since import"
    }
    Copy-Item -FromSession $s -Path (Invoke-Command -Session $s { Join-Path ([IO.Path]::GetTempPath()) 'top3.json' }) -Destination ~/pslab/tmp/top3.json
    Get-Content ~/pslab/tmp/top3.json | ConvertFrom-Json | Format-Table
}
finally {
    Invoke-Command -Session $s { Remove-Item (Join-Path ([IO.Path]::GetTempPath()) 'top3.json') -ErrorAction Ignore } -ErrorAction Ignore
    Remove-PSSession $s
}

Your numbers and process names will differ. The point is the finally: even if step 2 throws, the session and the temp file are removed.

Disconnect and reconnect: run the second command block. While it sleeps, open a second pwsh window and run Get-PSSession -ComputerName localhost — you will see the disconnected session from the other client.
Interactive (optional): Enter-PSSession -ComputerName localhost -ConfigurationName PowerShell.7, run $PID, Exit-PSSession, run $PID again: two different processes.
Cleanup: Get-PSSession | Remove-PSSession; Get-PSSession -ComputerName localhost | Remove-PSSession; Remove-Item ~/pslab/tmp/top3.json, ~/pslab/tmp/servers.fromsession.csv -ErrorAction Ignore

Case 1: “The WS-Management service cannot process the request … maximum number of concurrent shells”

Problem: After a week, a monitoring script could no longer connect to a jump server. Root cause: the script ran every 5 minutes, created New-PSSession and never removed it; each run's sessions stayed alive until the idle timeout, so the account hit the per-user shell quota. Fix: try { … } finally { Remove-PSSession $s }; for one-shot calls, use Invoke-Command -ComputerName (temporary session) instead.

Case 2: a 40-minute database export died when the VPN dropped

Problem: An engineer ran a long export in Enter-PSSession over VPN; the VPN reconnected and the session (and export) was gone. Root cause: an interactive session ties the remote work to the client connection. Fix: start long work with Invoke-Command -InDisconnectedSession, then Receive-PSSession after reconnecting — or run it as a scheduled task on the server (Module 7).

Case 3: copying a hotfix needed an admin share that security had disabled

Problem: Deployment scripts used Copy-Item \\srv\c$\Temp; a hardening baseline disabled admin shares and SMB from the management subnet. Fix: Copy-Item -ToSession over the existing WinRM session (port 5985/5986 only), followed by Get-FileHash on both sides inside the same session.

Common errors and fixes

The state of the current PSSession is not valid for this operation / session is Broken

Cause: network interruption, server reboot or idle timeout.

Get-PSSession | Format-Table Id, ComputerName, State, Availability

Fix: remove it and create a new one; design scripts to re-create sessions on Broken.

Copy-Item: Cannot find path … because it does not exist (with -ToSession)

Cause: the remote destination folder does not exist, or you mixed up local and remote paths.

Fix: create the folder remotely first (Invoke-Command -Session $s { New-Item … -Force }).

Enter-PSSession hangs when I run ssh, git or an installer

Cause: the remote host has no interactive console; native programs that wait for keyboard input block.

Fix: use non-interactive switches (-y, --batch, /quiet).

Disconnect-PSSession: … not supported (SSH session)

Cause: disconnected sessions are a WinRM feature.

Fix: on Linux use tmux/nohup or a systemd unit for long remote work.

Command-line exercises
1. Open sessions to two computers, run one command on both, and always remove them.
$s = New-PSSession -ComputerName srv1, srv2 -ConfigurationName PowerShell.7
try { Invoke-Command -Session $s { Get-Date } } finally { $s | Remove-PSSession }
2. Copy ./data/servers.csv to C:\Temp on a session and compare hashes remotely.
Copy-Item ./data/servers.csv -Destination C:\Temp -ToSession $s
$local = (Get-FileHash ./data/servers.csv).Hash
Invoke-Command -Session $s { (Get-FileHash C:\Temp\servers.csv).Hash -eq $using:local }
Scenario analysis
A runbook does 15 steps on each of 20 servers (stop service, copy files, update config, start service, verify). Temporary or persistent sessions? Why?

Persistent: 15 × 20 = 300 connections would cost minutes (≈0.7 s each on loopback, more over a WAN) and lose state between steps. Open 20 sessions once, run each step as Invoke-Command -Session $s (fan-out across all sessions, checking per-session errors), copy with -ToSession, and remove the sessions in finally. Drop a server's session from the array as soon as a step fails on it, so later steps do not run on a half-updated server.

Verified teaching videos

▶
PowerShell Master Class - PowerShell Remoting — John Savill's Technical Training
English · PSSessions, Enter-PSSession, implicit remoting

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–30s
Visual: ten handshakes vs one handshake and ten quick messages; timers 6.7 s vs 0.29 s.
Narration: a session pays the connection cost once.
Shot 2 · 30–60s
Visual: a file icon travelling inside the session tunnel; the SMB door stays closed.
Narration: Copy-Item To Session moves files over the same channel.
Shot 3 · 60–90s
Visual: laptop lid closes; the server keeps working; the laptop reopens and collects the result.
Narration: on WinRM, disconnect and come back later. Always remove your sessions.
or score ≥ 70% on the Quiz

Module 4 · SSH-based remoting across Windows, Linux and macOS

21:00 – 28:00 · The same Invoke-Command and New-PSSession, carried by SSH: sshd authenticates you with keys, then starts pwsh in server mode as a subsystem — one script can manage Windows, Linux and macOS
7 minMostly expected output (no sshd changes)★★★★☆
Learning objectives
  • Connect with -HostName, -UserName, -KeyFilePath, -Port and -Options; use -SSHConnection hashtables for mixed fleets.
  • Configure the server side: the Subsystem powershell … -sshs line in sshd_config on Windows (8.3 short path), Linux and macOS, plus key-based authentication.
  • Recognize the classic failures: “subsystem request failed on channel 0” (reproduced on the lab machine), host key prompts, wrong ssh client on PATH, password prompts in automation.
  • Compare SSH and WinRM remoting and choose per environment.
Prerequisites: Modules 1–3; SSH keys basics (Linux course). Importance:★★★★☆ (the only option for Linux/macOS and for non-domain Windows)

What: PSRP over an SSH channel

When you use -HostName, PowerShell starts the ssh client found on PATH with -s powershell (request the subsystem). sshd authenticates you (keys, password, or GSSAPI), looks up Subsystem powershell in sshd_config and starts that command — pwsh -sshs (“SSH server mode”: speak PSRP on stdin/stdout). From then on it is the same protocol as WinRM: objects, streams, sessions, Copy-Item -ToSession, all deserialized.

Client parameterMeaning
-HostName [user@]host[:port]Selects the SSH transport (instead of -ComputerName)
-UserNameRemote account; defaults to your local user name
-KeyFilePathPrivate key (or rely on ssh-agent / ~/.ssh/config)
-PortDefault 22
-SubsystemDefault powershell
-Options @{…} (7.3+)Any ssh -o option, e.g. BatchMode, StrictHostKeyChecking, ConnectTimeout
-SSHConnection @(@{HostName=…; UserName=…; KeyFilePath=…}, …)Different settings per host in one Invoke-Command/New-PSSession
-ConnectingTimeout (ms)Give up on unreachable hosts

Why: when SSH beats WinRM

  • Linux and macOS targets (no WinRM server there).
  • Workgroup/cloud Windows VMs without a domain: key authentication instead of NTLM + TrustedHosts or certificate-based HTTPS listeners.
  • One port (22) that firewalls and bastions already allow; existing SSH key management, jump hosts (ProxyJump in ~/.ssh/config) and auditing.

WinRM still wins for domain fleets that need endpoints, JEA, disconnected sessions or Kerberos delegation options (Module 7).

How: the server side (one-time admin setup — shown, not run)

OSsshd_config lineNotes
Windows (OpenSSH Server capability)Subsystem powershell c:/progra~1/powershell/7/pwsh.exe -sshs -NoLogoFile: %ProgramData%\ssh\sshd_config. Use the 8.3 short path: sshd does not accept spaces in the subsystem path. Administrators' keys go to %ProgramData%\ssh\administrators_authorized_keys (the Match Group administrators block)
LinuxSubsystem powershell /usr/bin/pwsh -sshs -NoLogo/etc/ssh/sshd_config; then sudo systemctl restart ssh (Debian/Ubuntu) or sshd (RHEL)
macOSSubsystem powershell /usr/local/bin/pwsh -sshs -NoLogoEnable Remote Login; path differs for Homebrew on Apple silicon (/opt/homebrew/bin/pwsh) — check with which pwsh

When: things that bite in automation

  • Prompts: unknown host key or password prompts hang a non-interactive job. Pre-populate known_hosts and use keys; pass -Options @{ BatchMode = 'yes' } so ssh fails instead of prompting.
  • Which ssh? PowerShell runs the first ssh on PATH. On the lab machine that is Git's OpenSSH_10.2p1, not Windows' OpenSSH_for_Windows_9.5p2 — different config and agent behavior.
  • Remote environment: the remote pwsh runs as the SSH user, with that account's home, PATH and modules — not yours. Import what you need inside the script block.
Common misconceptions① “SSH remoting needs WinRM” — it needs only sshd + pwsh. ② “Any sshd works once pwsh is installed” — without the Subsystem powershell line you get “subsystem request failed”. ③ “Windows PowerShell 5.1 can be the SSH server” — PowerShell 6+ only, on both ends. ④ “-ComputerName with SSH” — use -HostName (or -SSHTransport). ⑤ “It's slower than WinRM” — for most commands the difference is connection setup; reuse sessions exactly as in Module 3.

SSH remoting connection path

New-PSSession-HostName lin01-UserName ops -KeyFilePath ssh client (PATH)ssh -s … powershellknown_hosts · agent :22 sshdauthenticate (key)find Subsystem powershell pwsh -sshs -NoLogoruns as the SSH userPSRP over stdin/stdout fails herehost key prompt / no keywrong ssh on PATH fails herePermission denied(publickey,password) fails heresubsystem request failed on channel 0(no Subsystem line / bad path)
Figure 4-1: three stages, three distinct failure messages; the lab machine stops at the third (sshd runs, keys work, no PowerShell subsystem)

Where does the SSH connection fail?

Ready.
Real mechanism behind the animation PowerShell's SSH transport is a thin wrapper: it spawns the ssh client process and pipes PSRP through it. Anything ssh would ask interactively (passwords, host key confirmation) either appears on your console or — in a job — blocks. BatchMode=yes makes ssh fail instead.

Command table

CommandPurposeNotes
New-PSSession -HostName lin01 -UserName ops -KeyFilePath ~/.ssh/id_ed25519SSH sessionThen use it like any session
Invoke-Command -HostName lin01, lin02 { … }SSH fan-out-ThrottleLimit works the same
Invoke-Command -SSHConnection $hashtables { … }Per-host user/key/portKeys: HostName, UserName, KeyFilePath, Port, Subsystem, Options
-Options @{ BatchMode = 'yes'; ConnectTimeout = 5 }Never prompt; fail fast7.3+
(Get-Command ssh -All).SourceWhich ssh client will be usedFirst one wins
ssh -VClient versionPrints to stderr
# Read-only checks on the lab machine
Get-Service sshd, WinRM | Format-Table Name, Status, StartType
(Get-Command ssh -All).Source
& "$env:SystemRoot/System32/OpenSSH/ssh.exe" -V 2>&1 | ForEach-Object { "$_" }
Select-String -Path "$env:ProgramData/ssh/sshd_config" -Pattern '^\s*Subsystem' | ForEach-Object Line
# Try SSH remoting to localhost without changing anything (BatchMode: never prompt)
try {
    $s = New-PSSession -HostName localhost -ConnectingTimeout 8000 -ErrorAction Stop -Options @{
        BatchMode = 'yes'; StrictHostKeyChecking = 'no'; UserKnownHostsFile = 'NUL' }
    Remove-PSSession $s
} catch { "New-PSSession: $($_.Exception.Message)" }
Name   Status StartType
----   ------ ---------
sshd  Running Automatic
WinRM Running Automatic

C:\Program Files\Git\usr\bin\ssh.exe
C:\Windows\System32\OpenSSH\ssh.exe
OpenSSH_for_Windows_9.5p2, LibreSSL 3.8.2
Subsystem	sftp	sftp-server.exe
** WARNING: connection is not using a post-quantum key exchange algorithm.
** This session may be vulnerable to "store now, decrypt later" attacks.
** The server may need to be upgraded. See https://openssh.com/pq.html
subsystem request failed on channel 0
New-PSSession: The SSH client session has ended with error message: The SSH transport process has abruptly terminated causing this remote session to break.

How to read it: the key-based login succeeded (no “Permission denied”), but sshd has only the sftp subsystem, so the request for powershell fails and PowerShell reports a broken transport. The warning lines come from Git's newer ssh client (first on PATH) talking to the older Windows sshd. UserKnownHostsFile = 'NUL' + StrictHostKeyChecking = 'no' were used only so this probe would not write to the real known_hosts; do not use them against real servers.

Server setup (Expected — changes sshd; not run on the lab machine)

# Windows Server / Windows 11, elevated, on a lab machine only
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Add-Content -Path "$env:ProgramData\ssh\sshd_config" -Value 'Subsystem powershell c:/progra~1/powershell/7/pwsh.exe -sshs -NoLogo'
Restart-Service sshd
# Linux (Debian/Ubuntu), on a lab VM or container
sudo apt-get install -y openssh-server
echo 'Subsystem powershell /usr/bin/pwsh -sshs -NoLogo' | sudo tee -a /etc/ssh/sshd_config
sudo systemctl restart ssh
# Disposable Linux target for the lab (build and run on your own Docker host)
FROM mcr.microsoft.com/powershell:lts
RUN apt-get update && apt-get install -y openssh-server && mkdir -p /run/sshd \
 && echo 'Subsystem powershell /usr/bin/pwsh -sshs -NoLogo' >> /etc/ssh/sshd_config \
 && useradd -m -s /bin/bash ops && mkdir -p /home/ops/.ssh
COPY id_ed25519.pub /home/ops/.ssh/authorized_keys
RUN chown -R ops:ops /home/ops/.ssh && chmod 700 /home/ops/.ssh && chmod 600 /home/ops/.ssh/authorized_keys
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
# Client side, after: docker run -d --name pslinux -p 2222:22 pslab-ssh
$s = New-PSSession -HostName localhost -Port 2222 -UserName ops -KeyFilePath ~/.ssh/id_ed25519
Invoke-Command -Session $s { [pscustomobject]@{ OS = $PSVersionTable.OS; Edition = $PSVersionTable.PSEdition; User = whoami } }
Remove-PSSession $s
OS             : Ubuntu 24.04.x LTS
Edition        : Core
User           : ops
PSComputerName : localhost
RunspaceId     : …

Common mistake: forgetting that results from Linux are deserialized too, and that commands such as Get-Service do not exist there — write cross-platform script blocks ($IsLinux) or separate them per OS. Production use: keep host keys in a managed known_hosts, use per-environment keys in an agent or vault (Lesson 7), and set BatchMode=yes in every unattended call.

Goal: Diagnose an SSH remoting failure stage by stage. Environment: any machine with an ssh client; a container or VM target if you have one (Expected outputs otherwise). Safety: read-only on your own machine; any sshd change happens in a disposable container. Cost: none.

Which client? (Get-Command ssh -All).Source and ssh -V. If several are listed, decide which one PowerShell will use (the first).
Stage 1–2 (transport and authentication) without PowerShell:
ssh -o BatchMode=yes -o ConnectTimeout=5 ops@lin01 'echo auth-ok'

“auth-ok” → stages 1–2 work; “Permission denied (publickey…)” → key problem; “Host key verification failed” → known_hosts problem.

Stage 3 (subsystem): ssh -o BatchMode=yes ops@lin01 -s powershell — if it prints “subsystem request failed on channel 0”, the Subsystem line is missing or its path is wrong; otherwise you see PSRP XML (press Ctrl+C).
Build the container target (optional, Docker host): ssh-keygen -t ed25519 -f ./id_ed25519 -N '""' in an empty folder, save the Dockerfile above, docker build -t pslab-ssh ., docker run -d --name pslinux -p 2222:22 pslab-ssh, then run the client block.
Cleanup: Get-PSSession | Remove-PSSession; docker rm -f pslinux; delete the throw-away key pair.

Case 1: the nightly Linux inventory hung for 9 hours

Problem: A scheduled pwsh job ran Invoke-Command -HostName $linux { … }. A rebuilt VM had a new host key; ssh asked “Are you sure you want to continue connecting?” and waited forever. Fix: -Options @{ BatchMode = 'yes'; ConnectTimeout = 10 }, a managed known_hosts updated by the provisioning pipeline, and a task time limit (Module 7).

Case 2: works on the admin's laptop, fails on the build agent

Problem: New-PSSession -HostName failed on a Windows build agent with “ssh client not found / transport process terminated”. Root cause: the agent image had no OpenSSH client on PATH (the laptop used Git's). Fix: install the Windows OpenSSH client capability in the image and check Get-Command ssh in the pipeline's pre-flight step.

Case 3: subsystem path with spaces

Problem: After adding Subsystem powershell C:\Program Files\PowerShell\7\pwsh.exe -sshs, every connection failed. Root cause: sshd splits the line on spaces. Fix: the 8.3 path c:/progra~1/powershell/7/pwsh.exe as documented, then Restart-Service sshd.

Common errors and fixes

subsystem request failed on channel 0

Cause: no Subsystem powershell line, wrong path, or sshd not restarted (reproduced on the lab machine).

ssh user@host -s powershell

Fix: add the line for your OS and restart sshd (admin change on the target).

Permission denied (publickey,password,keyboard-interactive)

Cause: key not in authorized_keys (or, for Windows administrators, not in administrators_authorized_keys), wrong file permissions, wrong -UserName.

Fix: test with ssh -v; fix ACLs (chmod 600 on Linux; only SYSTEM and Administrators on the Windows administrators file).

The SSH client session has ended … transport process has abruptly terminated

Cause: generic: look at the ssh lines printed just before it (subsystem, auth, host key).

Fix: reproduce with plain ssh -o BatchMode=yes to see the real reason.

Host key verification failed / the job hangs on first connection

Fix: add the host key through a trusted channel (ssh-keyscan verified against the provisioning output), never blanket StrictHostKeyChecking=no in production.

Command-line exercises
1. Run uname -r on two Linux hosts with different users and keys in one call.
$c = @(
  @{ HostName = 'lin01'; UserName = 'ops';  KeyFilePath = '~/.ssh/ops_ed25519' }
  @{ HostName = 'lin02'; UserName = 'deploy'; KeyFilePath = '~/.ssh/deploy_ed25519'; Port = 2222 }
)
Invoke-Command -SSHConnection $c { uname -r }
2. Make an SSH remoting call fail within 5 seconds instead of prompting.
Invoke-Command -HostName lin01 -Options @{ BatchMode = 'yes'; ConnectTimeout = 5 } { hostname }
Scenario analysis
Your estate: 300 domain-joined Windows servers, 80 Ubuntu VMs, 20 workgroup Windows VMs in a DMZ. Which transport where?

Domain Windows: WinRM with Kerberos and PowerShell.7 endpoints (JEA, disconnected sessions available). Ubuntu: SSH with keys. DMZ workgroup Windows: SSH with keys (one port, no TrustedHosts/NTLM) — or WinRM over HTTPS with certificates if JEA is required. One script can cover all three: build session lists per group (New-PSSession -ComputerName / -HostName) and pass the combined array to Invoke-Command -Session.

Verified teaching videos

No verified video specific to PowerShell SSH remoting was found (searches returned only unverified or outdated material). Use the documentation and this module's diagnostics.

▶
PowerShell 7 Overview — John Savill's Technical Training
English · PowerShell 7 features overview (general background; recorded for 7.0)

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–30s
Visual: Windows, Linux and macOS logos connected by one SSH pipe; inside the pipe the same PSRP envelopes as Module 1.
Narration: SSH carries the same protocol to every OS.
Shot 2 · 30–65s
Visual: three checkpoints light up — ssh client, sshd authentication, Subsystem line; the third turns red with “subsystem request failed”.
Narration: three stages, three error messages. Missing subsystem is the classic one.
Shot 3 · 65–90s
Visual: a scheduled job frozen at a host-key prompt, then BatchMode=yes failing in two seconds.
Narration: automation never prompts — BatchMode yes.
or score ≥ 70% on the Quiz

Module 5 · Jobs: Start-Job, Start-ThreadJob, Receive-Job and job states

28:00 – 35:00 · A job runs a script block in the background and keeps its output until you collect it; whether it runs in another process or another thread decides its start-up cost and whether you get live or deserialized objects back
7 minAll runs real · local★★★★☆
Learning objectives
  • Compare the job types: Start-Job (child pwsh process, deserialized output, slow start), Start-ThreadJob (thread in your process, live objects, fast start; module Microsoft.PowerShell.ThreadJob in 7.6) and remote jobs (Invoke-Command -AsJob).
  • Read the job state machine: NotStarted → Running → Completed / Failed / Stopped (+ Blocked, Suspended, Disconnected), and HasMoreData.
  • Collect output correctly: Receive-Job -Wait -AutoRemoveJob, -Keep, Wait-Job -Timeout vs -Any, Stop-Job, Remove-Job.
  • Distinguish Failed (terminating error) from Completed with errors (non-terminating errors), and surface both.
Prerequisites: Module 1 (serialization); Lesson 5 (terminating vs non-terminating). Importance:★★★★☆

What: three kinds of background work

Start-JobStart-ThreadJobInvoke-Command -AsJob
Runs inA new pwsh process (PSRP over pipes)A new runspace on a thread of your processRemote runspaces
Start-up cost (measured, 5 jobs)1,834 ms561 msConnection cost (Module 2)
OutputDeserializedLive objectsDeserialized + PSComputerName
IsolationStrong: a crash or memory leak dies with the childWeak: shares the process; $using: gives referencesStrong (other machine)
ThrottlingNone built in-ThrottleLimit (default 5; queues the rest)-ThrottleLimit
PSJobTypeNameBackgroundJobThreadJobRemoteJob

Bash comparison: cmd & + wait + jobs give you a process and an exit code; output goes to the terminal or a file. PowerShell jobs buffer objects and all six streams until you Receive-Job them, and they live in the session's job table (Get-Job) — when the session ends, its jobs end too.

Why: the state machine and HasMoreData

StateMeaningWhat to do
NotStartedQueued (throttle) or not yet scheduledWait
RunningExecutingWait-Job, Receive-Job partial output
CompletedFinished — possibly with non-terminating errorsReceive output and check the error stream
FailedA terminating error ended itReceive-Job re-throws the error; or read $job.ChildJobs[0].JobStateInfo.Reason
StoppedStop-Job (or a timeout you implemented)Output so far is still receivable
BlockedWaiting for host input (a prompt!)Never prompt in jobs

HasMoreData is $true while unread output exists. A normal Receive-Job drains the buffer — a second call returns nothing; -Keep reads without draining.

How: the standard pattern

$jobs = $items | ForEach-Object { Start-ThreadJob -ThrottleLimit 8 -ArgumentList $_ { param($i) … } }
$null = $jobs | Wait-Job -Timeout 120                # returns only if ALL finished in time
$late = $jobs | Where-Object State -eq 'Running'; $late | Stop-Job
$results = $jobs | Receive-Job -ErrorVariable jobErr  # output + non-terminating errors
$failed  = $jobs | Where-Object State -eq 'Failed'
$jobs | Remove-Job -Force

When: which one to choose

  • ThreadJob for most local concurrency (I/O-bound calls, many small tasks) — and for anything where you want live objects back.
  • Start-Job when you need isolation: code that may crash, leak memory, change the current directory or environment globally, load conflicting assembly versions, or must run in Windows PowerShell 5.1 (Start-Job -PSVersion 5.1 on Windows).
  • Remote jobs when the work belongs on other machines (Module 2).
  • For a simple “do this for every item in parallel”, ForEach-Object -Parallel (Module 6) is shorter than managing jobs yourself.
Common misconceptions① “Completed means successful” — non-terminating errors leave the job Completed (verified below). ② “Wait-Job -Timeout returns the finished jobs” — without -Any it returns nothing if not all jobs finished in time (verified: 0 jobs). ③ “Receive-Job twice gives the output twice” — the first call drains it; use -Keep. ④ “ThreadJob is the old ThreadJob module” — in 7.6 it is Microsoft.PowerShell.ThreadJob (module-qualified name changed; the cmdlet name did not). ⑤ “Jobs survive closing the console” — they belong to the session; use scheduled tasks for that (Module 7).

Job types and where they run

Your pwsh process (PID 47476) Default runspaceyour prompt / scriptGet-Job job table ThreadJob runspacesame PID 47476live FileInfo ✓ -Parallel runspacessame PID, pooledModule 6 threads share memory → fast start, live objects, but no isolation $using: passes references (thread safety matters, Module 6) pipes + CLIXML Start-Job child processpwsh PID 46912≈ 0.3–0.4 s to start eachoutput: Deserialized.FileInfocrash isolated from parent Remote jobwsmprovhost on other machines
Figure 5-1: PIDs from this lesson's real run: the ThreadJob reported the caller's PID; Start-Job reported a different one

State machine

NotStarted Running end of script block Completed(maybe with errors!) terminating error Failed Stop-Job Stopped HasMoreDataTrue until Receive-Job drains it
Figure 5-2: “Completed” only says the script block reached its end

Job state machine

Ready.
Real mechanism behind the animation Every job object has a JobStateInfo and one or more child jobs that hold the actual output collections (Output, Error, Warning, Verbose, Information, Progress). Receive-Job moves items out of those collections into your pipeline and streams, which is why reading drains them.

Command table

CommandPurposeNotes
Start-Job { … } -WorkingDirectory pProcess job-PSVersion 5.1 runs it in Windows PowerShell (Windows)
Start-ThreadJob { … } -ThrottleLimit 8Thread jobThrottle applies to all ThreadJobs in the session
Get-JobJob tableFilter with -State, -Name
Receive-Job $j -Wait -AutoRemoveJobWait, collect, deleteThe most common one-liner
Receive-Job $j -KeepRead without drainingFor monitoring partial output
Wait-Job $j -Timeout 30 / -AnyBlock until all / any finishReturns nothing on timeout (without -Any)
Stop-Job, Remove-Job -ForceStop, deleteAlways clean up
# 1) Startup cost: process job vs thread job (trivial work, so we measure overhead)
$null = Start-Job { 1 } | Receive-Job -Wait -AutoRemoveJob          # warm-up
$null = Start-ThreadJob { 1 } | Receive-Job -Wait -AutoRemoveJob
$pj = Measure-Command { 1..5 | ForEach-Object { Start-Job { $PID } } | Receive-Job -Wait -AutoRemoveJob | Out-Null }
$tj = Measure-Command { 1..5 | ForEach-Object { Start-ThreadJob { $PID } } | Receive-Job -Wait -AutoRemoveJob | Out-Null }
'5 x Start-Job       : {0,6:N0} ms' -f $pj.TotalMilliseconds
'5 x Start-ThreadJob : {0,6:N0} ms' -f $tj.TotalMilliseconds

# 2) Where do they run, and what comes back?
$a = Start-Job       { [pscustomobject]@{ Pid = $PID; File = Get-Item $using:PSHOME/pwsh.dll } } | Receive-Job -Wait -AutoRemoveJob
$b = Start-ThreadJob { [pscustomobject]@{ Pid = $PID; File = Get-Item $using:PSHOME/pwsh.dll } } | Receive-Job -Wait -AutoRemoveJob
[pscustomobject]@{ Kind = 'caller';    Pid = $PID;  FileType = '-' },
[pscustomobject]@{ Kind = 'Start-Job';  Pid = $a.Pid; FileType = $a.File.pstypenames[0] },
[pscustomobject]@{ Kind = 'ThreadJob';  Pid = $b.Pid; FileType = $b.File.pstypenames[0] } | Format-Table
(Get-Command Start-ThreadJob).Source
5 x Start-Job       :  1,834 ms
5 x Start-ThreadJob :    561 ms

Kind        Pid FileType
----        --- --------
caller    47476 -
Start-Job 46912 Deserialized.System.IO.FileInfo
ThreadJob 47476 System.IO.FileInfo

Microsoft.PowerShell.ThreadJob

The ThreadJob time includes polling inside Receive-Job -Wait; the difference grows with the number of jobs because each Start-Job launches a full pwsh process (and loads modules again). Your numbers will differ; the ratio is what matters.

# 3) Job states, -Keep, Wait-Job -Timeout and failures
$ok   = Start-ThreadJob -Name ok   { 'line 1'; Start-Sleep -Milliseconds 300; 'line 2' }
$slow = Start-ThreadJob -Name slow { Start-Sleep -Seconds 30; 'never seen' }
$bad  = Start-ThreadJob -Name bad  { Get-Item ~/pslab/nope.txt -ErrorAction Stop }
$soft = Start-ThreadJob -Name soft { Get-Item ~/pslab/nope.txt; 'kept going' }

$done = Wait-Job -Job $ok, $bad, $soft, $slow -Timeout 3
'Wait-Job (all) returned : ' + @($done).Count + ' jobs'
$any = Wait-Job -Job $ok, $bad, $soft, $slow -Any -Timeout 3
'Wait-Job -Any returned  : ' + $any.Name
Get-Job | Sort-Object Id | Format-Table Id, Name, PSJobTypeName, State, HasMoreData

Receive-Job $ok -Keep          # read but keep the data
"HasMoreData after -Keep : $($ok.HasMoreData)"
$null = Receive-Job $ok
"HasMoreData after read  : $($ok.HasMoreData)"
"Receive again           : '$(Receive-Job $ok)'"

try { Receive-Job $bad -ErrorAction Stop } catch { "bad, rethrown: $($_.Exception.Message)" }
$out = Receive-Job $soft -ErrorVariable softErr 2>$null
"soft output : $out | errors: $($softErr.Count) | state: $($soft.State)"

Stop-Job $slow
"slow state  : $($slow.State)"
Get-Job | Remove-Job -Force
"jobs left   : $(@(Get-Job).Count)"
Wait-Job (all) returned : 0 jobs
Wait-Job -Any returned  : ok

Id Name PSJobTypeName State     HasMoreData
-- ---- ------------- -----     -----------
 1 ok   ThreadJob     Completed        True
 2 slow ThreadJob     Running          True
 3 bad  ThreadJob     Failed          False
 4 soft ThreadJob     Completed        True

line 1
line 2
HasMoreData after -Keep : True
HasMoreData after read  : False
Receive again           : ''
bad, rethrown: The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Cannot find path 'C:\Users\labadmin\pslab\nope.txt' because it does not exist.
soft output : kept going | errors: 1 | state: Completed
slow state  : Stopped
jobs left   : 0

How to verify: soft is Completed although it produced an error — only -ErrorVariable (or $soft.ChildJobs[0].Error) shows it. Common mistake: if ((Wait-Job $jobs -Timeout 60)) { … } else { 'all timed out' } — wrong: an empty result means not all finished. Production use: decide per job: Completed + no errors → success; Completed + errors → partial; Failed → failure; still Running after the deadline → Stop-Job and report as timeout.

Goal: Run a set of background tasks with a deadline and classify every job as success, partial, failed or timed out. Environment: any PowerShell 7.6. Cost: none.

Measure start-up: run block 1; try 20 jobs instead of 5 and compare the growth.
Classify jobs:
$specs = @{ fast = 'Start-Sleep -Milliseconds 200; "ok"'
            warn = 'Write-Error "disk 91%"; "ok-ish"'
            boom = 'throw "database unreachable"'
            hang = 'Start-Sleep -Seconds 20' }
$jobs = foreach ($k in $specs.Keys) { Start-ThreadJob -Name $k -ScriptBlock ([scriptblock]::Create($specs[$k])) }
$null = Wait-Job $jobs -Timeout 3
$report = foreach ($j in $jobs) {
    if ($j.State -eq 'Running') { Stop-Job $j }
    $out = Receive-Job $j -ErrorVariable e -ErrorAction SilentlyContinue 2>$null
    $status = if ($j.State -eq 'Stopped') { 'TimedOut' } elseif ($j.State -eq 'Failed') { 'Failed' } elseif ($e) { 'Partial' } else { 'Success' }
    [pscustomobject]@{ Job = $j.Name; State = $j.State; Status = $status; Output = "$out"; Errors = $e.Count }
}
$report | Sort-Object Job | Format-Table
$jobs | Remove-Job -Force
Job  State     Status   Output Errors
---  -----     ------   ------ ------
boom Failed    Failed               1
fast Completed Success  ok          0
hang Stopped   TimedOut             0
warn Completed Partial  ok-ish      1
Isolation test: a process job cannot touch your session; a thread job shares process-wide .NET state.
Set-Location ~/pslab; [Environment]::CurrentDirectory = (Get-Location).Path
Start-Job { Set-Location C:/; (Get-Location).Path } | Receive-Job -Wait -AutoRemoveJob
"parent location : …/$(Split-Path (Get-Location).Path -Leaf)"
"parent .NET dir : …/$(Split-Path ([Environment]::CurrentDirectory) -Leaf)"
Start-ThreadJob { [Environment]::CurrentDirectory = 'C:/' } | Receive-Job -Wait -AutoRemoveJob
"after ThreadJob : $([Environment]::CurrentDirectory)   <- process-wide, changed for everyone"
C:\
parent location : …/pslab
parent .NET dir : …/pslab
after ThreadJob : C:\   <- process-wide, changed for everyone

PowerShell's location is per runspace, but [Environment]::CurrentDirectory, environment variables ($env:) and static .NET fields are per process: a thread job or -Parallel block that changes them changes them for your whole session.

Cleanup: Get-Job | Remove-Job -Force

Case 1: “all backups completed” — three had failed

Problem: A wrapper started one job per database and reported success when every job's state was Completed. Three backups wrote “access denied” errors and produced no file. Root cause: non-terminating errors leave the job Completed. Fix: collect -ErrorVariable per job (or $j.ChildJobs.Error), treat “Completed with errors” as partial, and use -ErrorAction Stop inside the job where an error must fail it (Lesson 5).

Case 2: a monitoring loop leaked memory for weeks

Problem: A long-running pwsh service started a Start-Job every minute and only called Receive-Job. Root cause: jobs stay in the job table until removed; each held its output and child-process metadata. Fix: Receive-Job -Wait -AutoRemoveJob, or Remove-Job in finally; switch to ThreadJob to avoid one process per run.

Case 3: a job sat in “Blocked” for a whole weekend

Problem: A job called a function that used Read-Host for a missing value. Fix: make all inputs parameters, validate them before starting jobs, and add a deadline with Wait-Job -Timeout + Stop-Job.

Common errors and fixes

Receive-Job returns nothing

Cause: already received (drained), the job is still running, or output went to another stream.

Get-Job | Format-Table Id, Name, State, HasMoreData
$j.ChildJobs[0].Output.Count; $j.ChildJobs[0].Error

Fix: -Wait; use -Keep while monitoring.

The term 'X' is not recognized … inside a job

Cause: jobs start with a fresh runspace: your functions, variables and dot-sourced helpers are not there.

Fix: Import-Module inside the job, -InitializationScript (Start-Job / Start-ThreadJob), or $using: for values.

Start-ThreadJob: module ThreadJob not found (scripts written for 5.1 / older 7.x)

Cause: code that does Import-Module ThreadJob or uses ThreadJob\Start-ThreadJob.

Fix: in 7.6 the module is Microsoft.PowerShell.ThreadJob; just call Start-ThreadJob and let auto-loading find it.

Jobs never start (state stays NotStarted)

Cause: the ThreadJob throttle is full of long-running jobs.

Fix: raise -ThrottleLimit (the value from the first call applies session-wide) or stop/remove finished jobs.

Command-line exercises
1. Start three thread jobs that each sleep 1 s and return their name; collect all output and remove the jobs in one pipeline.
'a', 'b', 'c' | ForEach-Object { Start-ThreadJob -ArgumentList $_ { param($n) Start-Sleep 1; $n } } |
  Receive-Job -Wait -AutoRemoveJob
2. List jobs that finished with errors although their state is Completed.
Get-Job -State Completed | Where-Object { $_.ChildJobs.Error.Count -gt 0 }
Scenario analysis
You must run a vendor module that is known to crash the process now and then, for 50 tenants. ThreadJob or Start-Job?

Start-Job: a crash kills only the child process; the job becomes Failed and your controller keeps running. Pay the start-up cost (or batch several tenants per job), throttle manually (e.g. keep at most 8 running with Wait-Job -Any), and remember the output is deserialized — have the job return plain custom objects.

Verified teaching videos

No verified video dedicated to PowerShell 7 jobs and ThreadJob was found. The John Savill remoting episode touches remote jobs.

▶
PowerShell Master Class - PowerShell Remoting — John Savill's Technical Training
English · includes remote and background jobs (older PowerShell version)

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–30s
Visual: a process box spawning a child process (slow, heavy) vs spawning a thread (fast, light); stopwatch 1.8 s vs 0.56 s.
Narration: Start-Job is a process, ThreadJob is a thread.
Shot 2 · 30–60s
Visual: the state machine; a job with a red error badge still lands in green “Completed”.
Narration: Completed is not success. Check the error stream.
Shot 3 · 60–90s
Visual: a bucket of output emptied by Receive-Job; a second scoop finds nothing; “-Keep” leaves it full.
Narration: Receive drains. Wait with a deadline, stop the late ones, remove them all.
or score ≥ 70% on the Quiz

Module 6 · Parallelism: ForEach-Object -Parallel, thread safety and throttling

35:00 – 42:00 · -Parallel runs each input object's script block in its own runspace on a thread pool: great speed-ups for waiting-bound work, but nothing from your session is visible inside, and anything you share by reference can be corrupted by a race
7 minAll runs real · local★★★★★
Learning objectives
  • Use ForEach-Object -Parallel with -ThrottleLimit (default 5) and measure the speed-up for I/O-bound work (8 × 500 ms: 4.1 s → 1.2 s → 0.8 s).
  • Explain the runspace model: same process, separate runspaces; variables and functions from the caller are not visible; $using: passes values (and references for reference types).
  • Reproduce a lost-update race on a shared hashtable (251 of 500) and fix it with ConcurrentDictionary, ConcurrentBag or — best — by returning output instead of sharing state.
  • Use -TimeoutSeconds, -AsJob and -UseNewRunspace, and know that output arrives in completion order.
Prerequisites: Module 5. Importance:★★★★★ (OpsKit v0.4 is built on this)

What: a thread pool of runspaces

$items | ForEach-Object -Parallel { … } -ThrottleLimit N takes each input object, hands it to a runspace (at most N at once, each on its own thread), runs the script block with $_ set to that object, and streams all output back into your pipeline as iterations finish. Since 7.1 runspaces are reused from a pool (verified: 6 items with throttle 2 used 2 runspaces; -UseNewRunspace used 6). Bash analogue: xargs -P N or GNU parallel — but there each task is a process and returns text.

ParameterMeaningDefault
-Parallel { }Script block run per input object—
-ThrottleLimitMax concurrent runspaces5 (Invoke-Command: 32; ThreadJob: 5)
-TimeoutSecondsStop everything still running after N snone
-AsJobReturn a PSTaskJob (child per item) instead of output—
-UseNewRunspaceFresh runspace per item (no reuse)off

Why: three rules that cause most bugs

  1. Nothing is inherited. Each runspace starts with the default session state: no caller variables ($prefix → empty), no caller functions (Get-Label → not recognized), no modules imported by you (auto-loading of installed modules still works). Bring values with $using:, import your modules inside, or recreate a function from its definition string.
  2. $using: is not a copy for reference types. Unlike remoting and Start-Job (serialized copy), in -Parallel and ThreadJob $using:h gives every thread the same hashtable/list object. You cannot assign $using:x = … (parse error), but you can mutate the object — and that is a data race.
  3. Order is not preserved. Results come out as iterations finish. Sort afterwards or carry an index.

How: the race, precisely

$c.n = $c.n + 1 is three steps: read n, compute, write. Two threads that both read 41 both write 42: one increment is lost. With 8 threads and a little work between read and write, about half of 500 increments were lost in each of three runs (251, 252, 252). Hashtable, List[T], ArrayList and PowerShell arrays (+= creates a new array — still read-modify-write) are not safe for concurrent writers.

NeedSafe choice
Collect resultsJust output them from the block and assign the whole pipeline: $r = $x | ForEach-Object -Parallel { … }
Counters / keyed aggregation[System.Collections.Concurrent.ConcurrentDictionary[string,int]] with AddOrUpdate
Unordered bag of items[System.Collections.Concurrent.ConcurrentBag[T]] or ConcurrentQueue[T]
One shared fileReturn objects and write once at the end; or a [System.Threading.Mutex]/lock pattern (rarely worth it)

When: is it worth it?

  • Yes for waiting-bound work: network calls, health checks, remote APIs, DNS, file copies to many destinations. Speed-up ≈ min(items, throttle) until something else saturates.
  • No for tiny CPU work per item (adding numbers, string formatting): creating/scheduling runspaces costs milliseconds per item, far more than the work. Microsoft's parallel-execution performance article makes the same point: parallelism has a per-item cost.
  • Choose the throttle by the target: an API with a rate limit of 10 requests/s, a SAN that dislikes 64 parallel copies, a domain controller.
Common misconceptions① “Functions I defined are available inside -Parallel” — they are not (reproduced below). ② “$using: is always a copy” — it is a reference to the same object for ThreadJob and -Parallel. ③ “+= on a shared array is fine” — it is a read-modify-write race and also O(n²). ④ “Higher throttle is always faster” — beyond the bottleneck you only add overhead and load on the target. ⑤ “-TimeoutSeconds times out each item” — it stops the whole loop; unfinished items produce “The pipeline has been stopped.” errors.

Runspace pool and the shared object

Input1..500-ThrottleLimit 8 runspace Athread 26 · $_ = 1 runspace Bthread 25 · $_ = 2 runspace Cthread 24 · $_ = 3 … up to 8reused (7.1+) $using:h (same object!) @{ n = 0 }Hashtableread → work → writelost updates Concurrent-Dictionaryatomic AddOrUpdate Outputcompletion order6,5,4,3,2,1best: no sharing
Figure 6-1: all runspaces live in one process and see the same .NET object through $using:

Timeline of a lost update

A: read n = 41 B: read n = 41 A: work (SpinWait) B: work A: write n = 42 B: write n = 42 (lost +1) two increments, one effect — measured: 500 increments → n = 251
Figure 6-2: a read-modify-write on shared state without synchronization

Lost-update race, step by step

Ready.
Real mechanism behind the animation -Parallel creates a PSTaskPool with ThrottleLimit slots; each task gets a runspace, $using: values are captured when the task is created (for reference types, the reference), and output objects are written to a thread-safe buffer that the calling pipeline drains. Nothing makes your own shared objects safe.

Command table

CommandPurposeNotes
$x | ForEach-Object -Parallel { … } -ThrottleLimit 8Parallel loop7.0+
$using:varCaller's valueReference for reference types; read-only variable
${function:Name} = $using:defRecreate a function inside$def = ${function:Name}.ToString() outside
Import-Module $using:pathLoad your module insideWhat OpsKit v0.4 does
-TimeoutSeconds 30Overall deadlineStops remaining iterations
-AsJobBackgroundPSTaskJob; Receive-Job -Wait, then Remove-Job
[System.Collections.Concurrent.ConcurrentDictionary[string,int]]::new()Thread-safe mapAddOrUpdate, TryAdd, GetOrAdd
[System.Collections.Concurrent.ConcurrentBag[object]]::new()Thread-safe bagUnordered
# 1) Speed-up with simulated work (8 items x 500 ms)
$items = 1..8
$seq = Measure-Command { $items | ForEach-Object { Start-Sleep -Milliseconds 500 } }
$p5  = Measure-Command { $items | ForEach-Object -Parallel { Start-Sleep -Milliseconds 500 } }
$p8  = Measure-Command { $items | ForEach-Object -Parallel { Start-Sleep -Milliseconds 500 } -ThrottleLimit 8 }
'sequential        : {0,5:N0} ms' -f $seq.TotalMilliseconds
'-Parallel (def. 5): {0,5:N0} ms' -f $p5.TotalMilliseconds
'-Parallel -TL 8   : {0,5:N0} ms' -f $p8.TotalMilliseconds

# 2) Each iteration is a separate runspace in the SAME process
1..3 | ForEach-Object -Parallel {
    "item $_  pid $PID  runspace $([runspace]::DefaultRunspace.Id)  thread $([Environment]::CurrentManagedThreadId)"
} -ThrottleLimit 3 | Sort-Object

# 3) Variables and functions from the caller are not visible
$prefix = 'srv'
function Get-Label($n) { "label-$n" }
1 | ForEach-Object -Parallel { "prefix='$prefix'  using='$($using:prefix)'" }
1 | ForEach-Object -Parallel { Get-Label $_ } 2>&1 | ForEach-Object { "$_" }
# Workaround: pass the function definition as a string and recreate it
$def = ${function:Get-Label}.ToString()
1..2 | ForEach-Object -Parallel { ${function:Get-Label} = $using:def; Get-Label $_ }
sequential        : 4,103 ms
-Parallel (def. 5): 1,243 ms
-Parallel -TL 8   :   802 ms
item 1  pid 27076  runspace 15  thread 26
item 2  pid 27076  runspace 16  thread 25
item 3  pid 27076  runspace 17  thread 24
prefix=''  using='srv'
The term 'Get-Label' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
label-2
label-1

1,243 ms with the default throttle of 5 = two waves (5 + 3) of 500 ms plus overhead — the measured proof that the default is 5. Note the last two lines: label-2 finished before label-1.

# 4) You cannot assign to a $using: variable
1..3 | ForEach-Object -Parallel { $using:total += $_ }
ParserError: C:\Users\labadmin\pslab\scripts\demo.ps1:2
Line |
   2 |  1..3 | ForEach-Object -Parallel { $using:total += $_ }
     |                                    ~~~~~~~~~~~~
     | The assignment expression is not valid. The input to an assignment operator must be an object that is able to
     | accept assignments, such as a variable or a property.
# 5) A shared, non-thread-safe hashtable loses updates (run 3 times)
foreach ($run in 1..3) {
    $h = @{ n = 0 }
    1..500 | ForEach-Object -Parallel {
        $c = $using:h
        $v = $c.n                                  # read
        [System.Threading.Thread]::SpinWait(200000) # ~1 ms of work
        $c.n = $v + 1                              # write
    } -ThrottleLimit 8
    "run ${run}: plain hashtable n = $($h.n)   (expected 500)"
}

# 6) Thread-safe alternatives
$cd = [System.Collections.Concurrent.ConcurrentDictionary[string, int]]::new()
1..500 | ForEach-Object -Parallel {
    $d = $using:cd
    $null = $d.AddOrUpdate('n', 1, { param($key, $old) $old + 1 })
} -ThrottleLimit 8
"ConcurrentDictionary n = $($cd['n'])"

$bag = [System.Collections.Concurrent.ConcurrentBag[int]]::new()
1..500 | ForEach-Object -Parallel { ($using:bag).Add($_) } -ThrottleLimit 8
"ConcurrentBag count = $($bag.Count), sum = $(($bag | Measure-Object -Sum).Sum)"

# 7) Best: no shared state at all - output objects and let the caller collect them
$results = 1..500 | ForEach-Object -Parallel { $_ } -ThrottleLimit 8
"pipeline output count = $($results.Count)"
$order = 1..6 | ForEach-Object -Parallel { Start-Sleep -Milliseconds (700 - 100 * $_); $_ } -ThrottleLimit 6
"completion order: $($order -join ',')   (input order was 1..6)"
run 1: plain hashtable n = 251   (expected 500)
run 2: plain hashtable n = 252   (expected 500)
run 3: plain hashtable n = 252   (expected 500)
ConcurrentDictionary n = 500
ConcurrentBag count = 500, sum = 125250
pipeline output count = 500
completion order: 6,5,4,3,2,1   (input order was 1..6)

Honest note: without the SpinWait (a bare $c.n++), the first attempt lost only 2 of 2,000 updates in one of three runs — races are rare and timing-dependent, which is exactly why they survive testing. The small amount of work between read and write makes the window wide enough to see every time. Production use: pattern 7 (return output) first; concurrent collections when you really need shared aggregation.

# 8) -TimeoutSeconds, -AsJob and runspace reuse
$t = Measure-Command {
    $r = 1..4 | ForEach-Object -Parallel { Start-Sleep -Seconds $_; "done $_" } -TimeoutSeconds 2 -ErrorVariable toErr 2>$null
}
"results: $($r -join ', ')  after {0:N1} s" -f $t.TotalSeconds
"errors : $($toErr.Count) x '$($toErr[0].Exception.Message)'"

$j = 1..3 | ForEach-Object -Parallel { Start-Sleep -Milliseconds 300; $_ * 10 } -AsJob
$j | Format-Table Id, PSJobTypeName, State, @{ n = 'Children'; e = { $_.ChildJobs.Count } }
($j | Receive-Job -Wait | Sort-Object) -join ', '
$j | Remove-Job        # (-AutoRemoveJob here raised 'cannot remove … child job' on 7.6.10)

$ids  = 1..6 | ForEach-Object -Parallel { [runspace]::DefaultRunspace.Id } -ThrottleLimit 2
$ids2 = 1..6 | ForEach-Object -Parallel { [runspace]::DefaultRunspace.Id } -ThrottleLimit 2 -UseNewRunspace
"distinct runspaces, default        : $(@($ids  | Sort-Object -Unique).Count)"
"distinct runspaces, -UseNewRunspace: $(@($ids2 | Sort-Object -Unique).Count)"
results: done 1  after 2.1 s
errors : 3 x 'The pipeline has been stopped.'

Id PSJobTypeName State   Children
-- ------------- -----   --------
 1 PSTaskJob     Running        3

10, 20, 30
distinct runspaces, default        : 2
distinct runspaces, -UseNewRunspace: 6

When the demo first used Receive-Job -Wait -AutoRemoveJob on the PSTaskJob, 7.6.10 printed “The command cannot remove the job because it does not exist or because it is a child job…” after the output (the results were still returned). Receive, then Remove-Job the parent, as above.

Goal: Reproduce a race, fix it twice, and find the throttle sweet spot for a simulated API. Environment: any PowerShell 7.6. Cost: CPU for ~20 s during the race demo.

Race: run block 5. Then change SpinWait(200000) to SpinWait(0) and run again — how often do you still lose updates?
Fix 1 and 2: run block 6, then rewrite the counter without any shared object:
$n = (1..500 | ForEach-Object -Parallel { 1 } -ThrottleLimit 8 | Measure-Object -Sum).Sum
"n = $n"
n = 500
Throttle sweep: a “remote API” that takes 300 ms and allows at most 10 concurrent calls.
foreach ($tl in 1, 5, 10, 20) {
    $t = Measure-Command { 1..40 | ForEach-Object -Parallel { Start-Sleep -Milliseconds 300 } -ThrottleLimit $tl }
    '{0,2} -> {1,6:N0} ms' -f $tl, $t.TotalMilliseconds
}
 1 -> 12,562 ms
 5 ->  2,696 ms
10 ->  1,512 ms
20 ->  1,180 ms

The ideal numbers would be 12 s, 2.4 s, 1.2 s and 0.6 s; the gap grows with the throttle because runspace scheduling overhead becomes a larger share of each 300 ms task. Against the real API, 20 would also break its limit of 10. The right throttle is set by the target, not by your CPU.

Function visibility: run block 3 and then make Get-Label available by importing a tiny module file inside the block instead of the definition-string trick.
Cleanup: Get-Job | Remove-Job -Force

Case 1: the inventory report was 3% short — differently every night

Problem: A parallel collector did $list = [System.Collections.Generic.List[object]]::new(); $vms | ForEach-Object -Parallel { ($using:list).Add((Get-Info $_)) }. Some nights a few VMs were missing; once it threw “Destination array was not long enough”. Root cause: List[T].Add is not thread-safe; concurrent resizes lose items or throw. Fix: $list = $vms | ForEach-Object -Parallel { Get-Info $_ } — let the pipeline collect.

Case 2: parallel run was slower than sequential

Problem: Converting 200,000 log lines with -Parallel took 9 minutes instead of 20 seconds. Root cause: per-item runspace scheduling (milliseconds) vastly exceeded per-item CPU work (microseconds). Fix: sequential pipeline, or parallelize per file (coarse-grained chunks), not per line.

Case 3: an API locked the service account

Problem: -ThrottleLimit 64 against an identity API with a limit of 20 concurrent requests produced 429s, retries amplified them, and the account was throttled for an hour. Fix: throttle to the documented limit, honor Retry-After (Lesson 7), and put the limit in configuration, not in code.

Common errors and fixes

The term 'MyFunction' is not recognized … (inside -Parallel)

Cause: runspaces do not inherit functions.

$def = ${function:MyFunction}.ToString()
$x | ForEach-Object -Parallel { ${function:MyFunction} = $using:def; MyFunction $_ }

Fix: better: put the function in a module and Import-Module inside the block.

Variable is empty inside the block

Fix: $using:name.

The assignment expression is not valid … ($using:x += …)

Cause: $using: variables are read-only.

Fix: output values and aggregate after the loop, or mutate a concurrent collection.

Results differ from run to run / counts are too low

Cause: a race on shared state.

Fix: search the block for $using: on hashtables, lists, arrays or objects that are modified; replace with output or concurrent collections.

Command-line exercises
1. Resolve three DNS names in parallel (throttle 3) and keep the input order in the output.
$names = 'learn.microsoft.com', 'github.com', 'example.com'
$r = 0..($names.Count - 1) | ForEach-Object -Parallel {
  $n = ($using:names)[$_]
  [pscustomobject]@{ Index = $_; Name = $n; Ips = @([System.Net.Dns]::GetHostAddresses($n).IPAddressToString) }
} -ThrottleLimit 3
$r | Sort-Object Index | Select-Object Name, Ips
2. Count words per file across many files in parallel without shared state.
Get-ChildItem ~/pslab/data -File | ForEach-Object -Parallel {
  [pscustomobject]@{ File = $_.Name; Words = (Get-Content -LiteralPath $_.FullName -Raw -ErrorAction Ignore | Measure-Object -Word).Words }
} -ThrottleLimit 4 | Sort-Object File
Scenario analysis
A colleague's parallel script uses $using:results.Add(...) on a List[object] and “it always worked in testing with 10 servers”. Production has 900. What do you say?

It is a data race; with 10 items the chance of two concurrent Add calls overlapping during a resize is tiny, with 900 and more threads it becomes likely — symptoms are missing items or exceptions, not every time. Replace it with pipeline output ($results = $servers | ForEach-Object -Parallel { … }) or a ConcurrentBag; add a correctness check (input count = output count) to the script.

Verified teaching videos

▶
PowerShell 7 Overview — John Savill's Technical Training
English · PowerShell 7 new features (recorded for 7.0, when -Parallel was introduced)

No verified video focusing on thread safety in -Parallel was found; this module's race reproduction and the documentation below cover it.

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–25s
Visual: 8 sleeping tasks in one lane (4.1 s) vs five lanes (1.2 s) vs eight lanes (0.8 s).
Narration: parallel helps when you wait. Default throttle is five.
Shot 2 · 25–60s
Visual: two threads read 41, both write 42; a counter ends at 251 of 500.
Narration: shared objects plus parallel writers equals lost updates.
Shot 3 · 60–90s
Visual: the threads stop writing to the shared box and simply hand results to the pipeline.
Narration: don't share — output. If you must share, use concurrent collections.
or score ≥ 70% on the Quiz

Module 7 · Security and scheduling: credentials, double hop, JEA, Task Scheduler and cron

42:00 – 50:00 · Remote administration is only as safe as its credentials: never plaintext, understand why a remote session cannot reach a third machine with your identity, delegate narrowly with JEA, and run unattended work with the right switches and a time limit
8 minDouble hop reproduced · JEA/tasks authored, not registered★★★★☆
Learning objectives
  • Work with PSCredential objects (Get-Credential, -Credential, $using:cred) without ever putting a password in plaintext in a script, history or log; know where SecretManagement fits (Lesson 7).
  • Explain and recognize the double hop (reproduced: UnauthorizedAccessException from a remote session to a file share) and compare the options: CredSSP (and its risk), resource-based Kerberos constrained delegation, passing a credential explicitly, JEA with a run-as account.
  • Author a JEA role capability (.psrc) and session configuration (.pssc) and describe how they are registered and used.
  • Schedule pwsh -NoProfile -NonInteractive -File with Task Scheduler (New-ScheduledTask*), cron or a systemd timer, with a time limit and no overlapping runs.
Prerequisites: Modules 1–3; Lesson 1 Module 1 (startup switches). Importance:★★★★☆

What: credentials in PowerShell

A [pscredential] holds a user name and a [securestring] password. Cmdlets that accept -Credential take it directly; Get-Credential prompts for one (interactive only). Inside remote script blocks pass it with $using:cred (it is serialized securely within the encrypted PSRP channel). Rules:

  • No plaintext in scripts, parameters (-Password 'x' ends up in history and process listings), logs or transcripts.
  • ConvertTo-SecureString 'P@ss' -AsPlainText in a script defeats the purpose: the plaintext is in the file.
  • Export-Clixml of a credential encrypts it with DPAPI on Windows: only the same user on the same machine can read it; it is not encrypted on Linux/macOS. Prefer a vault via SecretManagement (Get-Secret) or managed identities/gMSAs — covered in Lesson 7 (SecretManagement was not installed on the lab machine, so it is not demonstrated here).
  • Best of all: no password at all — Kerberos with the current identity, gMSA for scheduled tasks, SSH keys, managed identity in the cloud.

Why: the double hop

You authenticate to server A with Kerberos (or NTLM). A gets a network logon for you, which can act on A but has no credential it can forward. When your remote script on A accesses B (a file share, SQL, another WinRM), A has nothing to present — B sees an anonymous or failed logon: Access is denied. Reproduced on the lab machine: the share is readable locally, and denied from a loopback remoting session.

OptionHowRisk / note
Pass a credential explicitlyInvoke-Command -ComputerName A { Get-ChildItem \\B\share -Credential … } or New-PSDrive -Credential $using:credSimple, scoped to the command; needs a credential object
Resource-based Kerberos constrained delegationOn B: Set-ADComputer B -PrincipalsAllowedToDelegateToAccount (Get-ADComputer A)Recommended for domains; no credentials stored on A; needs AD rights; does not work for WinRM-to-WinRM in all cases (see docs)
CredSSPEnable-WSManCredSSP on client and server, -Authentication CredSSPSends your reusable credential to A; if A is compromised, so is your account. Avoid; never to untrusted servers
JEA with a run-as identityThe endpoint runs as a virtual account (local) or gMSA (network access)The gMSA, not the user, accesses B; users get only the commands you allow
Kerberos unconstrained delegationTrust A for delegation in ADDangerous (A can impersonate users anywhere); do not use

How: Just Enough Administration (JEA)

  1. Role capability file (.psrc, in a module's RoleCapabilities folder): which cmdlets (and which parameter values), functions, external commands and providers a role may use.
  2. Session configuration file (.pssc): SessionType RestrictedRemoteServer (NoLanguage mode, minimal commands), RunAsVirtualAccount or GroupManagedServiceAccount, RoleDefinitions mapping AD groups to roles, TranscriptDirectory for auditing.
  3. Register on each server (admin change): Register-PSSessionConfiguration -Name OpsJea -Path .\OpsJea.pssc. Users then connect with -ConfigurationName OpsJea and see only their allowed commands — as a non-admin, while the commands run privileged.

When: scheduling unattended runs

PlatformMechanismMust-haves
WindowsTask Scheduler: New-ScheduledTaskAction / -Trigger / -SettingsSet → Register-ScheduledTaskRun as gMSA or a dedicated account (“run whether user is logged on or not”), ExecutionTimeLimit, MultipleInstances IgnoreNew
Linuxcron or a systemd timer + service unitAbsolute paths, flock or systemd's single instance, TimeoutStartSec, logs to journald
Everywherepwsh -NoProfile -NonInteractive -File script.ps1 -Param …Exit codes (Lesson 1), structured logs (Lesson 5), no prompts, explicit module imports
Common misconceptions① “Double hop is a bug in PowerShell” — it is how Windows network logons work; the fix is a delegation design. ② “Just enable CredSSP everywhere” — it hands your reusable password to every server you touch. ③ “JEA is a firewall” — it restricts what users can do in that endpoint; commands you allow (e.g. Start-Process, Invoke-Expression) can still be abused — allow narrowly and with ValidateSet. ④ “Export-Clixml credential files are portable” — DPAPI ties them to user and machine, and on Linux they are not encrypted. ⑤ “A scheduled task will tell me if it hangs” — set a time limit, or it runs forever.

The double hop and three ways around it

Admin PCyou: CONTOSO\opsTGT + credentials hop 1: Kerberos ✓ Server A (wsmprovhost)network logon as youcan act locallyno forwardable credential hop 2: ✗ Access denied Server B: \\fs01\sharesees no usable identityUnauthorizedAccessException RBKCD (on B)B trusts A to delegateno secrets on A ✓ recommended Explicit -Credential / $using:credscoped to one commandneeds a vaulted credential CredSSPyour password cached on AA compromised → you compromised
Figure 7-1: the second hop fails by design; choose a delegation mechanism deliberately

JEA: who runs what

Helpdesk usernon-admin-ConfigurationName OpsJea OpsJea.psscRestrictedRemoteServer (NoLanguage)RoleDefinitions: group → roleRunAsVirtualAccount / gMSATranscriptDirectory (audit)registered withRegister-PSSessionConfiguration OpsReader.psrcVisibleCmdlets: Get-ServiceRestart-Service -Name Spooler|W32TimeVisibleFunctions: Get-OpsHealtheverything else: not visibleruns as the privileged run-as account,logged as the real user
Figure 7-2: the files authored in this module's lab (nothing was registered)

Double-hop ticket flow

Ready.
Real mechanism behind the animation With Kerberos, server A receives a service ticket for HTTP/A, not your TGT, so it cannot request a ticket for cifs/B on your behalf unless delegation is configured (constrained/RBKCD uses S4U2Proxy). With NTLM there is never anything to forward. CredSSP solves it by sending the password itself.

Command table

CommandPurposeNotes
$cred = Get-Credential CONTOSO\opsPrompt for a credentialInteractive only
Invoke-Command -ComputerName A -Credential $credConnect as someone elseHop 1
New-PSDrive -Name S -PSProvider FileSystem -Root \\B\share -Credential $using:credExplicit credential on hop 2Inside the remote block
New-PSRoleCapabilityFile, New-PSSessionConfigurationFileAuthor JEA filesJust files
Test-PSSessionConfigurationFileValidate a .psscRead-only
Register-PSSessionConfiguration -Name X -Path x.psscCreate the endpointAdmin change (not run here)
New-ScheduledTaskAction/-Trigger/-SettingsSet, New-ScheduledTaskBuild a task in memoryNo change until Register-ScheduledTask
# The second hop: a remote session tries to reach a network share (lab machine, read-only)
$s = '\\fs01\Shares\home\labadmin\Documents'      # a share the user can read
"local: $(Test-Path $s)"
Invoke-Command -ComputerName $env:COMPUTERNAME -ConfigurationName PowerShell.7 {
    try { Get-ChildItem -LiteralPath $using:s -ErrorAction Stop | Select-Object -First 1 | ForEach-Object Name }
    catch { $_.Exception.GetType().FullName + ': ' + $_.Exception.Message }
}
local: True
System.UnauthorizedAccessException: Access to the path '\\fs01\Shares\home\labadmin\Documents' is denied.

The same test against \\LAB01\C$ (the lab machine itself) succeeded from the remote session — SMB back to the same machine is not a second hop. To see the problem you need a third machine, here the file server that hosts the user's redirected Documents folder. The remote session authenticated with Kerberos ([Security.Principal.WindowsIdentity]::GetCurrent().AuthenticationType = Kerberos).

# JEA authoring: create the two files only (registering them is an admin change we do NOT make here)
$jea = New-Item -ItemType Directory -Path ~/pslab/tmp/jea/OpsJea/RoleCapabilities -Force
New-PSRoleCapabilityFile -Path (Join-Path $jea 'OpsReader.psrc') `
    -VisibleCmdlets 'Get-Service', @{ Name = 'Restart-Service'; Parameters = @{ Name = 'Name'; ValidateSet = 'Spooler', 'W32Time' } } `
    -VisibleFunctions 'Get-OpsHealth' `
    -FunctionDefinitions @{ Name = 'Get-OpsHealth'; ScriptBlock = { Get-Service WinRM | Select-Object Name, Status } }
New-PSSessionConfigurationFile -Path ~/pslab/tmp/jea/OpsJea.pssc `
    -SessionType RestrictedRemoteServer -RunAsVirtualAccount `
    -RoleDefinitions @{ 'CONTOSO\OpsOperators' = @{ RoleCapabilities = 'OpsReader' } } `
    -TranscriptDirectory 'C:\ProgramData\JEA\Transcripts'
"pssc valid: $(Test-PSSessionConfigurationFile ~/pslab/tmp/jea/OpsJea.pssc)"
Get-ChildItem ~/pslab/tmp/jea -Recurse -File | Select-Object -ExpandProperty FullName
(Import-PowerShellDataFile ~/pslab/tmp/jea/OpsJea.pssc).GetEnumerator() |
    Where-Object Name -in 'SessionType', 'RunAsVirtualAccount', 'LanguageMode', 'TranscriptDirectory' | Sort-Object Name | Format-Table -AutoSize
pssc valid: True
C:\Users\labadmin\pslab\tmp\jea\OpsJea.pssc
C:\Users\labadmin\pslab\tmp\jea\OpsJea\RoleCapabilities\OpsReader.psrc

Name                Value
----                -----
RunAsVirtualAccount True
SessionType         RestrictedRemoteServer
TranscriptDirectory C:\ProgramData\JEA\Transcripts
Get-Content ~/pslab/tmp/jea/OpsJea/RoleCapabilities/OpsReader.psrc | Where-Object { $_ -notmatch '^\s*#' -and $_.Trim() }
@{
GUID = '6c81b47d-f08f-4cbd-bb25-5d2078e0f89b'
Author = 'labadmin'
CompanyName = 'Unknown'
Copyright = '(c) labadmin. All rights reserved.'
VisibleCmdlets = 'Get-Service', @{
    'Name' = 'Restart-Service'
    'Parameters' = @{
        'Name' = 'Name'
        'ValidateSet' = 'Spooler', 'W32Time' } }
VisibleFunctions = 'Get-OpsHealth'
FunctionDefinitions = @{
    'Name' = 'Get-OpsHealth'
    'ScriptBlock' = { Get-Service WinRM | Select-Object Name, Status } }
}

For a real endpoint, the OpsJea folder must be a module on $env:PSModulePath of the server (with a .psd1) so JEA can find RoleCapabilities\OpsReader.psrc. Then (admin, Expected): Register-PSSessionConfiguration -Name OpsJea -Path .\OpsJea.pssc and Enter-PSSession -ComputerName srv1 -ConfigurationName OpsJea → Get-Command lists only a handful of commands.

# Scheduling objects can be built in memory and inspected without registering anything
$action  = New-ScheduledTaskAction -Execute 'C:\Program Files\PowerShell\7\pwsh.exe' `
           -Argument '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File C:\ops\Invoke-Health.ps1 -Environment prod'
$trigger = New-ScheduledTaskTrigger -Daily -At '02:30'
$set     = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 30) -MultipleInstances IgnoreNew -StartWhenAvailable
$task    = New-ScheduledTask -Action $action -Trigger $trigger -Settings $set -Description 'OpsKit nightly health check'
$task.Actions[0] | Format-List Execute, Arguments
"trigger: $($task.Triggers[0].StartBoundary)  limit: $($task.Settings.ExecutionTimeLimit)  instances: $($task.Settings.MultipleInstances)"
Execute   : C:\Program Files\PowerShell\7\pwsh.exe
Arguments : -NoProfile -NonInteractive -ExecutionPolicy Bypass -File C:\ops\Invoke-Health.ps1 -Environment prod

trigger: 2026-11-24T07:30:00Z  limit: PT30M  instances: IgnoreNew
# Registering it (admin change; Expected, not run): run as a gMSA, no stored password
$task.Principal = New-ScheduledTaskPrincipal -UserId 'CONTOSO\gmsa-opskit$' -LogonType Password   # gMSA: AD manages the password
Register-ScheduledTask -TaskName 'OpsKit-Health' -TaskPath '\Ops\' -InputObject $task
# Linux: crontab -e (runs 02:30 daily; flock prevents overlapping runs)
30 2 * * * /usr/bin/flock -n /run/lock/opskit-health.lock /usr/bin/timeout 30m /usr/bin/pwsh -NoProfile -NonInteractive -File /opt/ops/Invoke-Health.ps1 -Environment prod >> /var/log/opskit-health.log 2>&1
# Linux: systemd timer (preferred) — /etc/systemd/system/opskit-health.service
[Unit]
Description=OpsKit nightly health check
[Service]
Type=oneshot
User=opskit
ExecStart=/usr/bin/pwsh -NoProfile -NonInteractive -File /opt/ops/Invoke-Health.ps1 -Environment prod
TimeoutStartSec=30min

# /etc/systemd/system/opskit-health.timer
[Unit]
Description=Run OpsKit health check daily
[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true
[Install]
WantedBy=timers.target
# enable (Expected): sudo systemctl daemon-reload && sudo systemctl enable --now opskit-health.timer

How to verify: Test-PSSessionConfigurationFile returns True; the task object shows the exact command line, limit and instance policy before anything is registered. Common mistake: scheduling pwsh script.ps1 without -NoProfile -NonInteractive — the profile of the service account loads, and a prompt hangs forever (Lesson 1, Case 1). Production use: scheduled scripts exit with meaningful codes, write JSON logs, and alert on non-zero exits; Task Scheduler's “Last Run Result” and systemctl status show them.

Goal: Author a JEA endpoint and a scheduled task definition, validate both, and (if you have a domain) reproduce the double hop. Environment: Windows PowerShell 7.6 for the JEA/task cmdlets; double hop needs WinRM + a file share on another machine. Safety: nothing is registered; files go to ~/pslab/tmp. Cost: none.

JEA files: run the JEA block; then add a second role OpsAdmin.psrc that may also run Restart-Computer -WhatIf only, and map it to another group.
Validate: Test-PSSessionConfigurationFile ~/pslab/tmp/jea/OpsJea.pssc → True. Introduce a typo (e.g. SessionType = 'Restricted') and run it again → False.
Task object: run the scheduling block; change the trigger to every 15 minutes (New-ScheduledTaskTrigger -Once -At 00:00 -RepetitionInterval (New-TimeSpan -Minutes 15)) and inspect $task.Triggers[0].Repetition. Do not register it.
Double hop (domain only): run the double-hop block against a share on a third machine. Then fix it for one command with an explicit credential:
$cred = Get-Credential CONTOSO\ops
Invoke-Command -ComputerName A -ConfigurationName PowerShell.7 {
    New-PSDrive -Name S -PSProvider FileSystem -Root '\\fs01\Shares' -Credential $using:cred | Out-Null
    Get-ChildItem S:\ | Select-Object -First 3 Name
}
Name     PSComputerName
----     --------------
home     A
public   A
…
Cleanup: Remove-Item -LiteralPath ~/pslab/tmp/jea -Recurse -Force

Case 1: CredSSP turned one compromised server into a domain incident

Problem: To “fix” double-hop errors, an operations team enabled CredSSP on all servers and used it from admin workstations. An attacker on one web server harvested the cached credentials of every admin who connected with CredSSP. Fix: disable CredSSP (Disable-WSManCredSSP), configure resource-based constrained delegation for the specific A→B pairs that need it, and move routine tasks to JEA endpoints with gMSA run-as accounts.

Case 2: helpdesk needed to restart a print spooler — and got Domain Admin

Problem: Helpdesk staff were added to local Administrators on 400 servers so they could restart the spooler. Fix: a JEA endpoint with one role capability (Restart-Service restricted by ValidateSet to Spooler), transcripts to a central share, and removal of the admin rights. Audit now shows who restarted what, under the virtual account.

Case 3: a password in a scheduled task's arguments

Problem: A task ran pwsh -File sync.ps1 -Password Summer2026!; the password was visible in Task Scheduler, process listings and the EDR's command-line telemetry. Fix: run the task as a gMSA so no password is needed; where a secret is unavoidable, read it inside the script from a vault (SecretManagement, Lesson 7) — never pass it on the command line.

Common errors and fixes

Access is denied / UnauthorizedAccessException only when running remotely

Cause: the double hop (accessing a second machine from the remote session).

Invoke-Command -ComputerName A { [Security.Principal.WindowsIdentity]::GetCurrent().AuthenticationType }

Fix: RBKCD, explicit -Credential for that resource, or a JEA endpoint with a gMSA.

Get-Credential: PowerShell is in NonInteractive mode…

Cause: prompting in a scheduled or CI run.

Fix: obtain secrets non-interactively (vault, managed identity, gMSA), or fail early with a clear message.

JEA: The term 'X' is not recognized (inside the JEA session)

Cause: not visible in any role the user has, or the role capability file is not in a module's RoleCapabilities folder on the server.

Get-PSSessionCapability -ConfigurationName OpsJea -Username CONTOSO\alice
Scheduled task shows “Running” forever / last result 0x41301

Cause: waiting for input or a hung call.

Fix: -NonInteractive, an ExecutionTimeLimit, timeouts on every network call (Lesson 5).

Command-line exercises
1. Build (do not register) a task that runs OpsKit's health check every weekday at 07:00 with a 10-minute limit.
$t = New-ScheduledTask -Action (New-ScheduledTaskAction -Execute pwsh.exe -Argument '-NoProfile -NonInteractive -File C:\ops\health.ps1') `
  -Trigger (New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday, Tuesday, Wednesday, Thursday, Friday -At 07:00) `
  -Settings (New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 10) -MultipleInstances IgnoreNew)
2. Write the cron line for the same schedule on Linux.
0 7 * * 1-5 /usr/bin/timeout 10m /usr/bin/pwsh -NoProfile -NonInteractive -File /opt/ops/health.ps1
Scenario analysis
A script on a jump server (reached by remoting) must copy logs from 30 app servers to a central share. It fails with access denied. Design a fix that does not use CredSSP.

Option A: run the collection on the jump server as a scheduled task under a gMSA that has read rights on the app servers and write rights on the share — no double hop, because the task's own identity accesses both. Option B: RBKCD so the share (and app servers) accept delegation from the jump server's computer account. Option C: Copy-Item -FromSession from each app server to the jump server, then write to the share with the jump server's identity. Avoid CredSSP and avoid storing a personal password.

Verified teaching videos

▶
Getting started with Just Enough Administration (JEA) by Jason Helmick — Confreaks
English · conference session: role capabilities, session configurations
▶
Securing your Environment with Just Enough Administration by James Petty — Confreaks
English · least-privilege delegation with JEA
▶
PowerShell Master Class - Automation — John Savill's Technical Training
English · automation technologies (scheduling, unattended runs)

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–30s
Visual: PC → server A (green) → file server B (red lock).
Narration: the second hop fails by design. A holds no credential it can forward.
Shot 2 · 30–60s
Visual: three doors: RBKCD (green), explicit credential (yellow), CredSSP (red, password leaking).
Narration: delegate narrowly; avoid CredSSP.
Shot 3 · 60–90s
Visual: a JEA endpoint showing only three commands; a scheduled task with a 30-minute timer and -NonInteractive badge.
Narration: JEA gives just enough. Scheduled runs: no profile, no prompts, a time limit.
or score ≥ 70% on the Quiz

Module 8 · OpsKit v0.4: Invoke-OpsHealthCheck in parallel across the inventory

50:00 – 60:00 · Put the lesson together: a pipeline-friendly advanced function that checks every server's health endpoint in parallel, with a per-server timeout, module import in each runspace, and one result object per server — verified against real local endpoints and unreachable inventory addresses
10 minAll runs real · 127.0.0.1 + 10.x timeouts★★★★★ milestone
Learning objectives
  • Upgrade OpsKit to v0.4: a hardened Test-OpsEndpoint (millisecond timeout, never throws, short stable error texts) and the new Invoke-OpsHealthCheck.
  • Design a parallel advanced function: collect pipeline input in process, run ForEach-Object -Parallel in end, import the module inside each runspace, pass parameters with $using:, emit typed result objects.
  • Build a reproducible local test bed: TCP endpoints on 127.0.0.1 that answer 200, 200-slow, 503, hang, plus a closed port and the 12 unreachable inventory servers.
  • Read the results: 17 servers in 2.5 s, 2 healthy; distinguish timeout, refused and HTTP errors; use the interactive troubleshooting tree.
Prerequisites: Modules 5–6; Lessons 3–5 (advanced functions, modules, error handling). Importance:★★★★★

What: the v0.4 contract

FunctionInputOutputChange in v0.4
Get-OpsServer-Environment, -PathOpsKit.Server: Name, Env, Region, IP, Role, Monitored, Portunchanged
Test-OpsEndpoint-Uri (alias HealthUrl, pipeline), -TimeoutMsOpsKit.EndpointResult: Uri, StatusCode, Healthy, ElapsedMs, Errormillisecond timeout via HttpClient; never throws; errors normalized to timeout after N ms, socket: ConnectionRefused, HTTP 503
Invoke-OpsHealthCheckObjects with IP+Port or HealthUrl (pipeline), -ThrottleLimit (8), -TimeoutMs (2000), -HealthPathOpsKit.HealthResult: Name, Env, Uri, Healthy, StatusCode, ElapsedMs, Error, Thread, CheckedAtnew

Why: the design decisions

  • Collect, then parallelize. process runs once per pipeline object; starting a parallel loop there would run one item at a time. So process only adds to a List[psobject]; end runs ForEach-Object -Parallel over the whole list.
  • Import the module in each runspace. Runspaces do not see the caller's functions (Module 6, reproduced again below). The function knows its own manifest path from $MyInvocation.MyCommand.Module.ModuleBase and passes it with $using:. With runspace reuse, each pooled runspace imports it once.
  • Every server gets exactly one result object — success or failure — so Results.Count equals input count and callers can filter on Healthy. No exceptions escape for an unhealthy server; that is data, not an error.
  • Timeout per request, throttle per run. Worst-case duration ≈ ceil(servers / throttle) × timeout. 17 servers, throttle 16, timeout 1.5 s → about 2 waves… measured 2.5 s.
  • No shared state. Results are pipeline output; nothing is written to a shared collection.

How: the test bed

TargetBehaviorExpected result
127.0.0.1:18081200 immediatelyHealthy
127.0.0.1:18082200 after 800 msHealthy, ElapsedMs ≈ 0.9–1.2 s
127.0.0.1:18083503Unhealthy, HTTP 503
127.0.0.1:18084nothing listeningsocket: ConnectionRefused (≈1 s on Windows, which retries refused loopback connections)
127.0.0.1:18085accepts, answers after 5 stimeout after 1500 ms
12 × 10.x.x.x:8080 from servers.csvunreachable from the labtimeout after 1500 ms

When: v0.4 vs remoting

Invoke-OpsHealthCheck tests endpoints from where you run it (like a load balancer probe) — no remoting needed. When a check must run on the server (disk, services), combine both: Invoke-Command -ComputerName … -ThrottleLimit 32 { … } with the same result-object design (Module 2), or call OpsKit inside a remote session.

Common misconceptions① “Put -Parallel in the process block” — you get no parallelism across pipeline items. ② “The module is loaded, so the runspaces have it” — they do not. ③ “Unhealthy servers should throw” — callers then lose the other results (Module 2's lesson again). ④ “A higher throttle always finishes faster” — it is bounded by the timeout and by the targets. ⑤ “ElapsedMs is precise” — the first call in a runspace includes JIT and module import (the 300 ms checks took ≈400–490 ms).

Invoke-OpsHealthCheck data flow

Get-OpsServer+ 5 lab targets17 objects process { }$targets.Add($item)(no work yet)manifest path from begin end { $targets | ForEach-Object -Parallel -ThrottleLimit 16 } runspace 1Import-Module$using:manifestTest-OpsEndpoint→ result object runspace 2same steps$using:TimeoutMsHttpClient1500 ms max … 16pooled, reusedno shared state OpsKit.HealthResult × 17 (completion order)Name · Env · Uri · Healthy · StatusCode · ElapsedMs · Error · CheckedAt Local test bed (127.0.0.1 only)18081 → 200 · 18082 → 200 after 800 ms18083 → 503 · 18084 → closed (refused)18085 → accepts, answers after 5 sTcpListener + Start-ThreadJob per port+ 12 inventory servers 10.x:8080 (timeouts)
Figure 8-1: process collects, end parallelizes; each runspace imports OpsKit and emits one result per server

One health check, from input object to result

Ready.

Interactive troubleshooting tree: my parallel / remote run gives wrong results

Step 1 · Test-OpsEndpoint v0.4 (~/pslab/OpsKit/Public/Test-OpsEndpoint.ps1)

function Test-OpsEndpoint {
    <#
    .SYNOPSIS
        Sends one HTTP GET to a health URL and returns a result object. Never throws.
    .EXAMPLE
        Test-OpsEndpoint -Uri http://127.0.0.1:18081/healthz -TimeoutMs 1500
    #>
    [CmdletBinding()]
    [OutputType('OpsKit.EndpointResult')]
    param(
        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [Alias('HealthUrl')]
        [uri]$Uri,

        [ValidateRange(100, 60000)]
        [int]$TimeoutMs = 2000
    )
    process {
        $sw = [System.Diagnostics.Stopwatch]::StartNew()
        $status = $null; $problem = $null
        $client = [System.Net.Http.HttpClient]::new()
        $client.Timeout = [timespan]::FromMilliseconds($TimeoutMs)
        try {
            $response = $client.GetAsync($Uri).GetAwaiter().GetResult()
            $status = [int]$response.StatusCode
            if ($status -lt 200 -or $status -ge 300) { $problem = "HTTP $status" }
        }
        catch {
            # Walk the exception chain: timeouts and socket errors get short, stable messages
            $chain = @(); $e = $_.Exception
            while ($e) { $chain += $e; $e = $e.InnerException }
            $socket = $chain | Where-Object { $_ -is [System.Net.Sockets.SocketException] } | Select-Object -First 1
            $problem = if ($chain | Where-Object { $_ -is [System.TimeoutException] -or $_ -is [System.Threading.Tasks.TaskCanceledException] }) {
                "timeout after $TimeoutMs ms"
            } elseif ($socket) { "socket: $($socket.SocketErrorCode)" }
            else { $chain[-1].Message }
        }
        finally { $client.Dispose() }
        [pscustomobject]@{
            PSTypeName = 'OpsKit.EndpointResult'
            Uri        = [string]$Uri
            StatusCode = $status
            Healthy    = ($status -ge 200 -and $status -lt 300)
            ElapsedMs  = [int]$sw.ElapsedMilliseconds
            Error      = $problem
        }
    }
}

Step 2 · Invoke-OpsHealthCheck (~/pslab/OpsKit/Public/Invoke-OpsHealthCheck.ps1)

function Invoke-OpsHealthCheck {
    <#
    .SYNOPSIS
        Checks the health endpoint of many servers in parallel.
    .DESCRIPTION
        Accepts server objects (from Get-OpsServer or any object with IP and Port, or HealthUrl),
        runs Test-OpsEndpoint for each one in its own runspace with ForEach-Object -Parallel,
        and returns one OpsKit.HealthResult per server. Results arrive in completion order.
    .EXAMPLE
        Get-OpsServer -Environment prod | Invoke-OpsHealthCheck -ThrottleLimit 16 -TimeoutMs 1500
    #>
    [CmdletBinding()]
    [OutputType('OpsKit.HealthResult')]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [psobject[]]$InputObject,

        [ValidateRange(1, 64)]
        [int]$ThrottleLimit = 8,

        [ValidateRange(100, 60000)]
        [int]$TimeoutMs = 2000,

        [string]$HealthPath = '/healthz'
    )
    begin {
        $targets  = [System.Collections.Generic.List[psobject]]::new()
        # Each runspace starts empty: it must import the module itself
        $manifest = Join-Path $MyInvocation.MyCommand.Module.ModuleBase 'OpsKit.psd1'
    }
    process {
        foreach ($item in $InputObject) { $targets.Add($item) }
    }
    end {
        if ($targets.Count -eq 0) { return }
        Write-Verbose "Checking $($targets.Count) endpoint(s), ThrottleLimit $ThrottleLimit, timeout $TimeoutMs ms"
        $targets | ForEach-Object -ThrottleLimit $ThrottleLimit -Parallel {
            Import-Module $using:manifest
            $server = $_
            $uri = if ($server.HealthUrl) { $server.HealthUrl }
                   else { 'http://{0}:{1}{2}' -f $server.IP, $server.Port, $using:HealthPath }
            $r = Test-OpsEndpoint -Uri $uri -TimeoutMs $using:TimeoutMs
            [pscustomobject]@{
                PSTypeName = 'OpsKit.HealthResult'
                Name       = $server.Name
                Env        = $server.Env
                Uri        = $r.Uri
                Healthy    = $r.Healthy
                StatusCode = $r.StatusCode
                ElapsedMs  = $r.ElapsedMs
                Error      = $r.Error
                Thread     = [System.Environment]::CurrentManagedThreadId
                CheckedAt  = [datetime]::UtcNow.ToString('o')
            }
        }
    }
}

Step 3 · Bump the manifest

Set-Location ~/pslab
Update-PSModuleManifest -Path ./OpsKit/OpsKit.psd1 -ModuleVersion '0.4.0' -FunctionsToExport @(
    'Get-OpsConfig', 'Get-OpsServer', 'Test-OpsEndpoint', 'Invoke-OpsBackup', 'Invoke-OpsHealthCheck')
Test-ModuleManifest ./OpsKit/OpsKit.psd1 | Format-List Name, Version, ExportedFunctions
Name              : OpsKit
Version           : 0.4.0
ExportedFunctions : {[Get-OpsConfig, Get-OpsConfig], [Get-OpsServer, Get-OpsServer], [Test-OpsEndpoint,
                    Test-OpsEndpoint], [Invoke-OpsBackup, Invoke-OpsBackup]…}

Update-PSModuleManifest comes from Microsoft.PowerShell.PSResourceGet (1.2.1 on the lab machine), the successor of PowerShellGet's Update-ModuleManifest (Lesson 4). The OpsKit.psm1 loader from Lesson 4 dot-sources Public/*.ps1 and exports their base names, so the new file is picked up automatically.

Step 4 · The local test bed (~/pslab/scripts/LabEndpoints.ps1)

# Tiny local HTTP endpoints for the Hour 6 labs (127.0.0.1 only, no admin rights needed).
# Dot-source this file, then:  $lab = Start-LabEndpoint ... ;  ... ;  Stop-LabEndpoint $lab
function Start-LabEndpoint {
    param(
        [Parameter(Mandatory)] [int]$Port,
        [int]$Status = 200,
        [int]$DelayMs = 0
    )
    $listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, $Port)
    $listener.Start()
    $job = Start-ThreadJob -Name "lab-$Port" -ScriptBlock {
        $l = $using:listener; $status = $using:Status; $delay = $using:DelayMs
        $reason = @{ 200 = 'OK'; 500 = 'Internal Server Error'; 503 = 'Service Unavailable' }[$status]
        while ($true) {
            try { $client = $l.AcceptTcpClient() } catch { break }     # Stop() ends the loop
            try {
                $stream = $client.GetStream()
                $reader = [System.IO.StreamReader]::new($stream)
                while ($reader.ReadLine()) { }                          # read the request headers
                if ($delay) { Start-Sleep -Milliseconds $delay }
                $body  = "{`"status`":$status,`"port`":$($using:Port)}"
                $bytes = [System.Text.Encoding]::ASCII.GetBytes(
                    "HTTP/1.1 $status $reason`r`nContent-Type: application/json`r`nContent-Length: $($body.Length)`r`nConnection: close`r`n`r`n$body")
                $stream.Write($bytes, 0, $bytes.Length)
            } catch { } finally { $client.Dispose() }
        }
    }
    [pscustomobject]@{ Port = $Port; Status = $Status; DelayMs = $DelayMs; Listener = $listener; Job = $job }
}

function Stop-LabEndpoint {
    param([Parameter(Mandatory, ValueFromPipeline)] $Endpoint)
    process {
        $Endpoint.Listener.Stop()
        $Endpoint.Job | Wait-Job -Timeout 5 | Out-Null
        $Endpoint.Job | Remove-Job -Force
    }
}

Step 5 · Run it

Set-Location ~/pslab
. ./scripts/LabEndpoints.ps1
Import-Module ./OpsKit/OpsKit.psd1 -Force

# Five local endpoints: healthy, slow, failing, hanging; port 18084 is deliberately NOT started
$eps = @(
    Start-LabEndpoint -Port 18081 -Status 200
    Start-LabEndpoint -Port 18082 -Status 200 -DelayMs 800
    Start-LabEndpoint -Port 18083 -Status 503
    Start-LabEndpoint -Port 18085 -Status 200 -DelayMs 5000
)
$lab = @(
    [pscustomobject]@{ Name = 'lab-ok';      Env = 'lab'; IP = '127.0.0.1'; Port = 18081 }
    [pscustomobject]@{ Name = 'lab-slow';    Env = 'lab'; IP = '127.0.0.1'; Port = 18082 }
    [pscustomobject]@{ Name = 'lab-503';     Env = 'lab'; IP = '127.0.0.1'; Port = 18083 }
    [pscustomobject]@{ Name = 'lab-refused'; Env = 'lab'; IP = '127.0.0.1'; Port = 18084 }
    [pscustomobject]@{ Name = 'lab-hang';    Env = 'lab'; IP = '127.0.0.1'; Port = 18085 }
)
Test-OpsEndpoint -Uri http://127.0.0.1:18081/healthz | Format-List

$all = @($lab) + @(Get-OpsServer -Path ./data/servers.csv)
$t = Measure-Command {
    $results = $all | Invoke-OpsHealthCheck -ThrottleLimit 16 -TimeoutMs 1500
}
$results | Sort-Object Env, Name | Format-Table Name, Env, Healthy, StatusCode, ElapsedMs, Error -AutoSize
'{0} servers, {1} healthy, {2:N1} s total' -f $results.Count, @($results | Where-Object Healthy).Count, $t.TotalSeconds
$eps | Stop-LabEndpoint
Uri        : http://127.0.0.1:18081/healthz
StatusCode : 200
Healthy    : True
ElapsedMs  : 90
Error      :


Name        Env     Healthy StatusCode ElapsedMs Error
----        ---     ------- ---------- --------- -----
api-01      dev       False                 1770 timeout after 1500 ms
db-01       dev       False                 1743 timeout after 1500 ms
web-01      dev       False                 1738 timeout after 1500 ms
lab-503     lab       False 503                7 HTTP 503
lab-hang    lab       False                 1631 timeout after 1500 ms
lab-ok      lab        True 200               12
lab-refused lab       False                 1168 socket: ConnectionRefused
lab-slow    lab        True 200              943
api-01      prod      False                 1819 timeout after 1500 ms
bastion-01  prod      False                 1646 timeout after 1500 ms
db-01       prod      False                 1815 timeout after 1500 ms
edge-01     prod      False                 1798 timeout after 1500 ms
web-01      prod      False                 1819 timeout after 1500 ms
web-02      prod      False                 1721 timeout after 1500 ms
api-01      staging   False                 1750 timeout after 1500 ms
db-01       staging   False                 1712 timeout after 1500 ms
web-01      staging   False                 1727 timeout after 1500 ms

17 servers, 2 healthy, 2.5 s total

How to verify: 17 in, 17 out; exactly lab-ok and lab-slow healthy; every 10.x server is a timeout, not an exception. Timeouts show 1.6–1.8 s instead of 1.5 s because the stopwatch also covers runspace start-up, module import and HttpClient creation. What went wrong first (real): the first version classified errors by the innermost exception only — lab-hang came out as “The I/O operation has been aborted because of either a thread exit…” and lab-refused as a long socket message. Walking the whole exception chain and checking for TimeoutException/TaskCanceledException and SocketException gave the short, stable texts above.

Why the import inside the runspace is required

Set-Location ~/pslab
Import-Module ./OpsKit/OpsKit.psd1 -Force
Get-Module OpsKit | Format-Table Name, Version, @{ n = 'Functions'; e = { $_.ExportedFunctions.Keys -join ', ' } } -Wrap
# Why the module must be imported INSIDE each runspace:
1 | ForEach-Object -Parallel { Test-OpsEndpoint -Uri http://127.0.0.1:18081/ } 2>&1 | ForEach-Object { "$_" }
1 | ForEach-Object -Parallel { "modules loaded in the runspace: '$((Get-Module).Name -join ', ')'" }
# -Verbose and the empty-input case
Get-OpsServer -Path ./data/servers.csv -Environment dev | Invoke-OpsHealthCheck -TimeoutMs 300 -Verbose |
    Format-Table Name, Healthy, ElapsedMs, Error
@() | Invoke-OpsHealthCheck
"empty input -> no output, no error: $?"
Name   Version Functions
----   ------- ---------
OpsKit 0.4.0   Get-OpsConfig, Get-OpsServer, Invoke-OpsBackup, Invoke-OpsHealthCheck, Test-OpsEndpoint

The term 'Test-OpsEndpoint' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
modules loaded in the runspace: ''
VERBOSE: Checking 3 endpoint(s), ThrottleLimit 8, timeout 300 ms

Name   Healthy ElapsedMs Error
----   ------- --------- -----
web-01   False       435 timeout after 300 ms
api-01   False       412 timeout after 300 ms
db-01    False       404 timeout after 300 ms

empty input -> no output, no error: True

OpsKit is loaded from a path, not from $env:PSModulePath, so module auto-loading cannot rescue the runspace. Once OpsKit is installed from your local repository (Lesson 4), auto-loading inside runspaces would find it — the explicit Import-Module $using:manifest still guarantees the same version as the caller.

Goal: Ship OpsKit v0.4 and prove it works on healthy, slow, failing, closed, hanging and unreachable targets. Environment: any PowerShell 7.6; no admin rights (listeners bind to 127.0.0.1 with TcpListener). Cost: none.

Add the files: save Step 1 and Step 2 into ~/pslab/OpsKit/Public/ (replacing the v0.3 Test-OpsEndpoint.ps1), and Step 4 as ~/pslab/scripts/LabEndpoints.ps1.
Bump the version: run Step 3; Test-ModuleManifest must show 0.4.0.
Run: Step 5. Check: 17 results, 2 healthy, total time under 3 s (with throttle 16).
Explore the throttle: run again with -ThrottleLimit 4 and predict the time first (17 targets, 15 slow ones of ≈1.5 s → about 4–5 waves ≈ 6–8 s). Measured on the lab machine: 17 servers, 2 healthy, 6.7 s total.
Pipeline friendliness: Get-OpsServer -Path ./data/servers.csv -Environment prod | Invoke-OpsHealthCheck -TimeoutMs 500 | Where-Object { -not $_.Healthy } | Select-Object Name, Error
Cleanup: $eps | Stop-LabEndpoint; Get-Job | Remove-Job -Force — then confirm the ports are free: Get-NetTCPConnection -LocalPort 18081 -State Listen -ErrorAction Ignore returns nothing.

Case 1: the health check took 25 minutes during an outage

Problem: A sequential check of 600 endpoints with the default 100-second HTTP timeout took minutes on a normal day and 25 minutes when a network segment was down — the dashboard was stale exactly when it mattered. Fix: v0.4's design: parallel with a throttle of 32, a 2-second per-request timeout, one result per target. Worst case became ceil(600/32) × 2 s ≈ 38 s.

Case 2: “all green” while 40 servers were down

Problem: A previous parallel checker wrote results with $using:results.Add() to a List[object] and occasionally lost items; missing servers were not shown at all, so the dashboard was green. Fix: pipeline output only, plus a contract check: if ($results.Count -ne $targets.Count) { throw 'result count mismatch' }.

Case 3: the checker DDoSed its own load balancer

Problem: -ThrottleLimit 200 every 30 seconds from three monitoring hosts saturated the connection table of a small internal load balancer. Fix: throttle in configuration (Health.Throttle in opskit.config.psd1), stagger schedules, and cache results for 30 s.

Common errors and fixes

The term 'Test-OpsEndpoint' is not recognized (inside -Parallel)

Cause: the runspace did not import OpsKit (reproduced above).

Fix: Import-Module $using:manifest as the first line of the parallel block.

Every result is “timeout” — even for healthy servers

Cause: -TimeoutMs lower than the first-call overhead (JIT + import ≈ 100–400 ms), a proxy, or a firewall dropping packets.

Test-OpsEndpoint -Uri http://127.0.0.1:18081/healthz -TimeoutMs 5000
[System.Net.Http.HttpClient]::DefaultProxy
Start-LabEndpoint: Only one usage of each socket address … is normally permitted

Cause: the port is still in use (previous run not stopped).

Fix: $eps | Stop-LabEndpoint; or close the pwsh window that started them; pick other ports.

Result count is smaller than input count

Cause: an exception escaped a runspace, or -TimeoutSeconds stopped the loop.

Fix: keep Test-OpsEndpoint's never-throw contract; avoid loop-level timeouts, rely on per-request timeouts.

Command-line exercises
1. Show only unhealthy prod servers with their error, sorted by name.
Get-OpsServer -Environment prod | Invoke-OpsHealthCheck -TimeoutMs 1000 |
  Where-Object { -not $_.Healthy } | Sort-Object Name | Format-Table Name, Error
2. Group all results by error text and count them.
$results | Group-Object { if ($_.Healthy) { 'OK' } else { $_.Error } } -NoElement | Sort-Object Count -Descending
Scenario analysis
Management wants the health check to also report free disk space on each server. Extend v0.4's design without breaking it.

Disk space must be measured on the server, so it needs remoting: add a separate function (e.g. Get-OpsDiskReport) that uses Invoke-Command -ComputerName … -ConfigurationName PowerShell.7 -ThrottleLimit 32 -ErrorVariable and returns one object per server (including unreachable ones). Keep Invoke-OpsHealthCheck as the network-level probe. A wrapper can join both result sets on Name/Env. Do not make the endpoint check depend on WinRM availability.

Verified teaching videos

▶
PowerShell 7 Overview — John Savill's Technical Training
English · PowerShell 7 features including parallel ForEach-Object

No verified video builds a parallel health-check module like this one; the module code and outputs on this page are the reference.

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–30s
Visual: 17 server cards enter a funnel (process collects), then fan out into 16 lanes (end parallelizes).
Narration: collect in process, parallelize in end.
Shot 2 · 30–60s
Visual: each lane opens a toolbox labelled “Import-Module OpsKit” before calling Test-OpsEndpoint; one lane without it shows a red “not recognized”.
Narration: every runspace imports the module itself.
Shot 3 · 60–90s
Visual: a results table, 2 green and 15 red rows, stopwatch 2.5 s.
Narration: one result per server, a timeout per request — the whole inventory in seconds.
or score ≥ 70% on the Quiz

Command cheat sheet

All Lesson 6 key points: transports and endpoints, serialization, fan-out, sessions, SSH, jobs, parallelism, security and scheduling
PowerShell 7.6Copyable

1. Transports, endpoints, serialization

Test-WSMan srv1                         # WinRM listener?
Get-PSSessionConfiguration              # endpoints (elevated)
$PSSessionConfigurationName = 'PowerShell.7'   # default is 5.1!
$x.pstypenames[0]                       # Deserialized.* ?
[System.Management.Automation.PSSerializer]::Serialize($o, 1)
Invoke-Command srv1 { Get-Item x | Select-Object Name, @{n='Dir';e={$_.Directory.Name}} }

2. Fan-out

$r = Invoke-Command -ComputerName $list -ConfigurationName PowerShell.7 `
      -ThrottleLimit 32 -ErrorAction SilentlyContinue -ErrorVariable fe { … $using:x … }
$fe | Select-Object TargetObject, FullyQualifiedErrorId
$list | Where-Object { $_ -notin $r.PSComputerName }   # missing hosts
-AsJob · -HideComputerName · -ArgumentList (,$array)

3. Sessions

$s = New-PSSession -ComputerName a, b -ConfigurationName PowerShell.7
try { Invoke-Command -Session $s { … } } finally { $s | Remove-PSSession }
Enter-PSSession srv1 ; Exit-PSSession          # humans only
Copy-Item f.zip -Destination C:\Temp -ToSession $s
Copy-Item C:\log.txt -Destination . -FromSession $s
Invoke-Command srv1 -InDisconnectedSession -SessionName x { … }
Receive-PSSession -ComputerName srv1 -Name x -OutTarget Job | Receive-Job -Wait
Import-PSSession $s -Module X -Prefix Remote     # implicit remoting

4. SSH remoting

New-PSSession -HostName lin01 -UserName ops -KeyFilePath ~/.ssh/id_ed25519
Invoke-Command -HostName lin01 -Options @{ BatchMode='yes'; ConnectTimeout=5 } { … }
Invoke-Command -SSHConnection @(@{HostName='a';UserName='u';KeyFilePath='k'}) { … }
(Get-Command ssh -All).Source                   # which client?
# sshd_config:
# Subsystem powershell /usr/bin/pwsh -sshs -NoLogo
# Subsystem powershell c:/progra~1/powershell/7/pwsh.exe -sshs -NoLogo

5. Jobs

Start-Job { … }            # process, deserialized, isolated
Start-ThreadJob { … } -ThrottleLimit 8   # thread, live objects
$j | Receive-Job -Wait -AutoRemoveJob
Receive-Job $j -Keep                     # don't drain
Wait-Job $j -Timeout 60    # returns NOTHING unless all done
Wait-Job $j -Any
Get-Job -State Completed | Where-Object { $_.ChildJobs.Error.Count }
Get-Job | Remove-Job -Force

6. -Parallel and thread safety

$r = $x | ForEach-Object -Parallel { … $using:v … } -ThrottleLimit 8   # default 5
${function:F} = $using:def          # $def = ${function:F}.ToString()
Import-Module $using:manifest
-TimeoutSeconds 30 · -AsJob · -UseNewRunspace
[System.Collections.Concurrent.ConcurrentDictionary[string,int]]::new()
$d.AddOrUpdate('k', 1, { param($k, $old) $old + 1 })
# never: ($using:list).Add() on List/Hashtable/ArrayList

7. Credentials, double hop, JEA

$cred = Get-Credential               # never -AsPlainText in scripts
Invoke-Command A { New-PSDrive S FileSystem \\B\s -Credential $using:cred }
Set-ADComputer B -PrincipalsAllowedToDelegateToAccount (Get-ADComputer A)  # RBKCD
New-PSRoleCapabilityFile -Path X.psrc -VisibleCmdlets …
New-PSSessionConfigurationFile -Path X.pssc -SessionType RestrictedRemoteServer -RunAsVirtualAccount
Test-PSSessionConfigurationFile X.pssc
Register-PSSessionConfiguration -Name X -Path X.pssc    # admin

8. Scheduling and OpsKit v0.4

pwsh -NoProfile -NonInteractive -File C:\ops\health.ps1
New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 30) -MultipleInstances IgnoreNew
# cron:  30 2 * * * flock -n /run/lock/x timeout 30m pwsh -NoProfile -NonInteractive -File /opt/x.ps1
# systemd: Type=oneshot + TimeoutStartSec + .timer OnCalendar=
Get-OpsServer -Environment prod | Invoke-OpsHealthCheck -ThrottleLimit 16 -TimeoutMs 1500 |
  Where-Object { -not $_.Healthy }

Integrated lab + final quiz

Compare three ways to check the whole inventory — sequential, one ThreadJob per server, and OpsKit v0.4's ForEach-Object -Parallel — for speed and for correctness
about 25 minLocal onlyIntegrates M1–M8

Scenario

Before adopting v0.4 in the on-call runbook, the team wants evidence: is the parallel version actually faster, and does it give exactly the same verdict for every server as the slow, obviously-correct sequential loop? Write ~/pslab/scripts/Compare-HealthCheck.ps1 that starts the local test bed, checks the same 17 targets three ways with the same 1,500 ms timeout, and prints duration, result count, healthy count and an order-independent correctness check.

The script (M5, M6, M8; uses LabEndpoints.ps1 and OpsKit v0.4):
<#
.SYNOPSIS
    Integrated lab, Lesson 6: sequential vs Start-ThreadJob vs ForEach-Object -Parallel health checks.
.DESCRIPTION
    Starts the local test bed, checks the same targets three ways with the same timeout,
    and compares duration, counts and per-server verdicts (order-independent).
#>
#Requires -Version 7.4
Set-Location ~/pslab
. ./scripts/LabEndpoints.ps1
Import-Module ./OpsKit/OpsKit.psd1 -Force
$eps = @(
    Start-LabEndpoint -Port 18081 -Status 200
    Start-LabEndpoint -Port 18082 -Status 200 -DelayMs 800
    Start-LabEndpoint -Port 18083 -Status 503
    Start-LabEndpoint -Port 18085 -Status 200 -DelayMs 5000
)
$lab = 18081, 18082, 18083, 18084, 18085 | ForEach-Object {
    [pscustomobject]@{ Name = "lab-$_"; Env = 'lab'; IP = '127.0.0.1'; Port = $_ }
}
$targets = @($lab) + @(Get-OpsServer -Path ./data/servers.csv)
$timeout = 1500

# A) sequential
$seq = Measure-Command {
    $rSeq = foreach ($s in $targets) {
        $r = Test-OpsEndpoint -Uri "http://$($s.IP):$($s.Port)/healthz" -TimeoutMs $timeout
        [pscustomobject]@{ Key = "$($s.Env)/$($s.Name)"; Healthy = $r.Healthy; Error = $r.Error }
    }
}
# B) one thread job per server, throttled
$tj = Measure-Command {
    $manifest = (Resolve-Path ./OpsKit/OpsKit.psd1).Path
    $jobs = foreach ($s in $targets) {
        Start-ThreadJob -ThrottleLimit 16 -ArgumentList $s, $manifest, $timeout -ScriptBlock {
            param($s, $manifest, $timeout)
            Import-Module $manifest
            $r = Test-OpsEndpoint -Uri "http://$($s.IP):$($s.Port)/healthz" -TimeoutMs $timeout
            [pscustomobject]@{ Key = "$($s.Env)/$($s.Name)"; Healthy = $r.Healthy; Error = $r.Error }
        }
    }
    $rTj = $jobs | Receive-Job -Wait -AutoRemoveJob
}
# C) OpsKit v0.4: ForEach-Object -Parallel inside Invoke-OpsHealthCheck
$par = Measure-Command {
    $rPar = $targets | Invoke-OpsHealthCheck -ThrottleLimit 16 -TimeoutMs $timeout |
        ForEach-Object { [pscustomobject]@{ Key = "$($_.Env)/$($_.Name)"; Healthy = $_.Healthy; Error = $_.Error } }
}
$eps | Stop-LabEndpoint

# Correctness: same keys, same verdicts, regardless of completion order
function ConvertTo-Verdict($rows) { ($rows | Sort-Object Key | ForEach-Object { "$($_.Key)=$($_.Healthy)" }) -join ';' }
$ref = ConvertTo-Verdict $rSeq
@(
[pscustomobject]@{ Method = 'Sequential';      Seconds = [math]::Round($seq.TotalSeconds, 1); Results = $rSeq.Count; Healthy = @($rSeq | Where-Object Healthy).Count; SameAsSequential = $true }
[pscustomobject]@{ Method = 'Start-ThreadJob'; Seconds = [math]::Round($tj.TotalSeconds, 1);  Results = $rTj.Count;  Healthy = @($rTj  | Where-Object Healthy).Count; SameAsSequential = (ConvertTo-Verdict $rTj) -eq $ref }
[pscustomobject]@{ Method = '-Parallel (v0.4)'; Seconds = [math]::Round($par.TotalSeconds, 1); Results = $rPar.Count; Healthy = @($rPar | Where-Object Healthy).Count; SameAsSequential = (ConvertTo-Verdict $rPar) -eq $ref }
) | Format-Table -AutoSize

Design notes: each method produces the same shape (Key, Healthy, Error); ConvertTo-Verdict sorts by key so completion order does not matter (Module 6); ThreadJobs import the module themselves (Module 5); the job variant uses -ArgumentList/param() instead of $using: to show the alternative.

Run it:
Set-Location ~/pslab
./scripts/Compare-HealthCheck.ps1
Method           Seconds Results Healthy SameAsSequential
------           ------- ------- ------- ----------------
Sequential         21.70      17       2             True
Start-ThreadJob     4.00      17       2             True
-Parallel (v0.4)    2.40      17       2             True

Sequential ≈ 15 timeouts × 1.5 s + the slow endpoint. ThreadJob is slower than -Parallel here mainly because of job bookkeeping and the Receive-Job -Wait polling, with the same throttle of 16. Exact seconds vary between runs (an earlier run gave 21.7 / 3.9 / 2.3).

Break it on purpose (correctness check must catch it): in the -Parallel branch, change Healthy = $_.Healthy to Healthy = $_.StatusCode -eq 200 -or $_.StatusCode -eq 503; rerun — SameAsSequential becomes False for that row. Revert.
Prove the race risk is absent: confirm that no branch writes to a shared collection (search the script and Invoke-OpsHealthCheck for $using: on lists or hashtables — there is none; $using: only carries strings and numbers such as the manifest path and the timeout, and the ThreadJob branch passes values with -ArgumentList).
Cleanup: the script stops its endpoints; additionally run Get-Job | Remove-Job -Force; Get-PSSession | Remove-PSSession.
Acceptance criteria

Open-ended self-check

1. Trace a FileInfo from Invoke-Command -ComputerName srv1 { Get-Item C:\x.log } to your console.

The remote runspace (endpoint chosen by -ConfigurationName or the 5.1 default) produces a live FileInfo; the PSRP server serializes its properties to CLIXML up to the serialization depth (Directory becomes a string), captures ToString(); the client deserializes into a PSObject with type names Deserialized.System.IO.FileInfo…, adds PSComputerName/RunspaceId/PSShowComputerName, and the formatting system picks a view for the deserialized type. Methods are gone.

2. When would you choose Start-Job over Start-ThreadJob, and what do you pay for it?

For isolation (crash-prone or leaking code, process-wide state changes, Windows PowerShell 5.1 via -PSVersion 5.1). You pay process start-up (measured 1.8 s vs 0.56 s for five jobs) and deserialized output.

3. Why does Invoke-OpsHealthCheck collect input in process and run -Parallel in end?

Because process sees one pipeline object at a time; running the parallel loop there would process each object alone. Collecting first lets -Parallel distribute all targets across the throttle.

4. A remote script must read a file share. List three designs and their trade-offs.

RBKCD (no secrets on the middle server; needs AD changes), explicit -Credential for that resource (simple; needs a vaulted credential), JEA endpoint or scheduled task running as a gMSA (no personal credentials; more setup). Not CredSSP (exposes reusable credentials).

Sources and version notes

Facts were checked on 2026-11-24 against Microsoft Learn and YouTube oEmbed; command outputs were produced on PowerShell 7.6.10 on a Windows 11 machine where WinRM loopback was already enabled
Verification date 2026-11-24
TopicVerified resultSources (accessed 2026-11-24)
Remoting architecture, endpointsDefault WinRM endpoint from pwsh 7.6.10 answered Desktop 5.1.26100.10068; -ConfigurationName PowerShell.7 answered Core 7.6.10 in a wsmprovhost process; pwsh lists PowerShell.7 and per-patch PowerShell.7.6.x endpointsWS-Management remoting in PowerShell; about_Remote; this lesson's runs
SerializationFileInfo → Deserialized.System.IO.FileInfo, 23 → 2 methods, Directory becomes a string; Int/String/DateTime/TimeSpan/Guid/Version/IPAddress rehydrated; Hashtable real but tagged Deserializedabout_Remote_Output; runs with PSSerializer, Start-Job, Invoke-Command
Invoke-CommandThrottleLimit default 32 (documented); measured 6 × 2 s loopback: 3.3 s (TL 6) vs 8.6 s (TL 2); -ErrorAction Stop on a fan-out left the result variable unassignedInvoke-Command; about_Remote_Variables
Sessions10 calls: 6,727 ms fresh vs 287 ms reused; Copy-Item -ToSession/-FromSession hash-identical; -InDisconnectedSession + Receive-PSSession -OutTarget Job worked on loopback; implicit remoting returns deserialized objectsNew-PSSession; about_Remote_Disconnected_Sessions; Running remote commands
SSH remotingLab sshd (OpenSSH_for_Windows_9.5p2) had only the sftp subsystem → “subsystem request failed on channel 0”; first ssh on PATH was Git's OpenSSH_10.2p1; Subsystem lines and setup from the docs (not applied)PowerShell remoting over SSH
Jobs5 × Start-Job 1,834 ms vs 5 × Start-ThreadJob 561 ms; Start-ThreadJob from Microsoft.PowerShell.ThreadJob 2.2.0; non-terminating error → Completed; Wait-Job -Timeout (all) returned 0 jobsabout_Jobs; about_Thread_Jobs; Start-ThreadJob
-ParallelDefault throttle 5 (8 × 500 ms → 1,243 ms); functions not visible; $using: assignment is a parse error; shared Hashtable lost ≈ half of 500 updates (251/252/252); ConcurrentDictionary/Bag correct; -TimeoutSeconds → “The pipeline has been stopped.”; runspace reuse 2 vs -UseNewRunspace 6ForEach-Object; Parallel execution
Double hop, JEA, schedulingDouble hop reproduced (UnauthorizedAccessException to a file share from a Kerberos loopback session); JEA .psrc/.pssc authored and validated (not registered); scheduled-task objects built in memory (not registered)Second hop; JEA overview; JEA role capabilities; Register-ScheduledTask; SecretManagement
OpsKit v0.417 targets in 2.5 s (throttle 16, 1,500 ms), 6.7 s with throttle 4; integrated lab 21.7 / 4.0 / 2.4 s with identical verdictsThis lesson's runs

Video verification notes

Only videos whose titles and channels were checked via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-24 are listed:

oEmbed verifies titles and channels only; the videos were not watched segment by segment, and the “meta” descriptions come from titles, the course repository index and public information. They predate PowerShell 7.6 (some use Windows PowerShell 5.1); where behavior differs, this lesson is authoritative. One candidate JEA video (xnBrbkY9P20) returned “Forbidden” from oEmbed and is not listed. No verified video was found specifically for SSH remoting in PowerShell 7, ThreadJob/job states, or thread safety in -Parallel.

Voice narration notes

The “Voice” tab uses the browser's built-in Web Speech API to read the narration script (en-US); it needs no network access or external scripts. The courseware cannot embed MP3 files or generate video; the narration and storyboards can be passed to a TTS or video tool.

Known limitations

  • Run environment: Windows 11, PowerShell 7.6.10 (.NET 10.0.15), elevated, domain-joined, WinRM already running with an HTTP listener, Kerberos available, and TrustedHosts = * on the lab machine (a pre-existing lab setting; it is why 127.0.0.1 succeeded in Module 2). On a default machine, IP-address targets fail and Get-PSSessionConfiguration needs elevation. Machine name replaced with LAB01, user paths with C:\Users\labadmin\…, the file server with \\fs01, and the generated JEA file's author with labadmin.
  • Not run (Expected output): Enable-PSRemoting, any WinRM/TrustedHosts/firewall change, Enter-PSSession (interactive), installing/configuring sshd and a successful SSH remoting session (Linux container, Windows OpenSSH server), Get-Credential and anything needing a typed credential, the double-hop fix with -Credential, RBKCD and CredSSP, Register-PSSessionConfiguration and using a JEA endpoint, Register-ScheduledTask, cron and systemd timers, SecretManagement (module not installed on the lab machine). OpsKit v0.3 interface listing in Module 0 is expected output from Lesson 5.
  • Not run on Linux or macOS: SSH targets, Subsystem paths and systemd/cron syntax come from the documentation and standard Linux practice.
  • OpsKit stand-ins: the lab used minimal stand-ins for Get-OpsServer, Get-OpsConfig and Invoke-OpsBackup with the interface listed in Module 0, because Lessons 3–5 are authored separately; Test-OpsEndpoint v0.4, Invoke-OpsHealthCheck and LabEndpoints.ps1 are printed in full and are exactly the code that produced the outputs.
  • Timings depend on the machine and the moment; ratios are the point. The race demo uses a deliberate ~1 ms busy-wait between read and write to make lost updates reproducible; without it, losses were rare (2 of 2,000 in one of three runs).
  • The 10.x inventory addresses timed out from the lab network; on a network where they route or are refused, the error texts differ (socket: … instead of timeout after … ms).
  • The animations simplify PSRP (message fragmentation, key exchange, runspace pool sizes) and Kerberos (S4U2Self/S4U2Proxy details).