A script that keeps going after an error as if nothing had happened is more dangerous than one that crashes: at the end it reports "done" over half-finished work. This lesson shows how PowerShell sorts errors, how you turn them into exceptions you catch, and why native programs (git, az, dotnet, any .exe) follow a rule of their own. At the end stands a trap that has caught experienced script writers too.

All examples were run with PowerShell 7.6.9 on Windows 11; the output comes from that run (system messages in English, path shortened). A file that does not exist is called does-not-exist.txt in the examples.

Two kinds of errors

PowerShell knows non-terminating and terminating errors. A non-terminating error is reported, and the command, the script, the pipeline keep going:

PowerShell
Get-Item ./does-not-exist.txt
'afterwards'
Get-Item: C:\work\l0203a.ps1:3
Line |
   3 |  Get-Item ./does-not-exist.txt
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot find path
     | 'C:\work\does-not-exist.txt' because it does not exist.
afterwards

afterwards appears despite the error. A terminating error (an exception) aborts the current block and looks for a catch. Most cmdlet errors are non-terminating because with a list of a hundred files they should not stop at the first failure. For a runbook you almost always want the opposite.