Retry a transient remote operation
Documentation: Microsoft Learn
Retry Invoke-Command up to three times with increasing delays. Use terminating error handling and rethrow the final failure.
The script
$Computer = "SRV01"$Script = { Get-Service -Name Spooler -ErrorAction Stop }for($i = 1; $i -le 3; $i ++){ try { Invoke-Command -ComputerName $Computer -ScriptBlock $Script -ErrorAction Stop; break } catch { if($i -eq 3){ throw }; Start-Sleep -Seconds (5 * $i) } }Script reader
Inspect before you run
Inspect the script below. It does not run in this browser.
Inspection only — no command has run.
Show reference output
Status Name DisplayName PSComputerName------ ---- ----------- --------------Running Spooler Print Spooler SRV01Inspect this example’s structure
Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.
$Computer = "SRV01"
$Script = { Get-Service -Name Spooler -ErrorAction Stop }
for($i = 1; $i -le 3; $i ++){ try { Invoke-Command -ComputerName $Computer -ScriptBlock $Script -ErrorAction Stop; break }
catch { if($i -eq 3){ throw }; Start-Sleep -Seconds (5 * $i) } }- Stage 1$Computer
Positional values or no named parameters
How it works
A counted for loop makes up to three attempts. Invoke-Command runs with -EA Stop so a remoting failure becomes a terminating error the catch block can see, break exits the loop on success, and the catch rethrows on the third attempt while otherwise sleeping five seconds multiplied by the attempt number.
Adapting it
This bounded read-only demonstration retries every exception. A production policy should retry only errors classified as transient, stop on authentication or validation failures, and preserve the original error. Avoid retrying writes unless their outcome and safe repetition are established.
Requirements
WinRM reachable on the target plus rights to run the script block there.
If the result is unexpected
A retry loop repeats a permanent error or performs an operation twice.
Authentication and validation failures are not transient, and a timed-out write may already have completed.
- Classify the error and check authoritative state before retrying a potentially completed write.
Validate the result
Verify a service object is returned from the intended server, or that the final failure is surfaced after at most three attempts. This example does not log each attempt. Add structured attempt logging when adapting it for unattended use.
Keep the check reliable
Design retried operations for safe repetition and apply backoff only to suitable failures.