A terminating exception stops the current operation and transfers control to exception-handling code. PowerShell commands usually need -ErrorAction Stop before their failures can be caught; otherwise, they may emit a nonterminating error and continue. section 15.1 section 15.4
Use terminating exceptions deliberately:
- Set -ErrorAction Stop on the command whose failure you need to handle, rather than changing the global $ErrorActionPreference. section 15.1
- Wrap dependent work in Try/Catch; once the Try block fails, its remaining statements are skipped and Catch runs. section 15.4
- Process one computer or other failure-prone item at a time, because stopping one batch can prevent later items from being attempted. section 15.4
- Use Catch to warn, log, retry with another protocol, or abandon work that depends on the failed operation. section 15.4
Catching a failed connection
Try { $params = @{ ComputerName = $computer; SessionOption = $option; ErrorAction = 'Stop' }; $session = New-CimSession @params; $os = Get-CimInstance -ClassName Win32_OperatingSystem -CimSession $session } Catch { Write-Warning "FAILED $computer on $protocol" } section 15.4
Get-Service -Name BITS, Nobody, WinRM -EA Continue Get-Service -Name BITS, Nobody, WinRM -EA SilentlyContinue Get-Service -Name BITS, Nobody, WinRM -EA Inquire Get-Service -Name BITS, Nobody, WinRM -EA Ignore Get-Service -Name BITS, Nobody, WinRM -EA Stop
Compare Continue, SilentlyContinue, Inquire, Ignore, and Stop while running a command against valid and invalid services. section 15.1
Methods without -ErrorAction, such as many .NET Framework methods, commonly throw terminating exceptions directly. Temporarily setting $ErrorActionPreference to Stop is a last-resort technique for catching other operations. section 15.6
