A try/catch statement protects an operation that may fail without abandoning the rest of an automation. Put the operation in try; when it produces a terminating error, execution skips the remaining try code and enters catch. With no error, catch is skipped. An optional finally block runs last in either path. section 6.1.1
In PowerShell, catch handles terminating errors. Many command errors are nonterminating, so add -ErrorAction Stop when a failure must enter catch. The triggering error is available as $_, allowing catch to distinguish an expected condition from an unexpected failure. section 6.1.1 section 6.1.1
Continue service processing while preserving unexpected failures
A service lookup can fail because the named service does not exist. Capture that error, test $_.FullyQualifiedErrorId, and allow that expected case to pass; send any other error to Write-Error or throw it. This lets later services continue when one service cannot be processed. section 6.1.1
$s = "localhost"
try{
$session = New-PSSession -ComputerName $s -ErrorAction Stop
$Sessions.Add($session)
}
catch{
Write-Host "$($s) failed to connect: $($_)"
}
This pattern creates a remote session only when New-PSSession succeeds. -ErrorAction Stop routes connection failures to catch, preventing failed sessions from entering the collection used by Invoke-Command. section 5.3.3
Use try/catch to make automation decisions from known failures rather than suppressing them:
- Capture and evaluate an error instead of using -ErrorAction SilentlyContinue, which can hide causes such as missing permissions. section 6.1
- Keep successful remote sessions in the session array so one failed connection does not prevent commands from running on reachable servers. section 5.3.3
- Take a specific action for recognized errors and report or rethrow unrecognized ones when later work may still continue. section 6.1.1 section 6.4









