An exception is a runtime problem that interrupts normal PowerShell execution and gives code an opportunity to respond. PowerShell commands often emit nonterminating errors and continue, so handling requires converting the relevant error into a terminating exception. section 15.1 section 15.3
Use exceptions when a failure needs an active response:
- Set -ErrorAction Stop on the command that may fail, rather than globally suppressing errors. section 15.1 section 15.4
- Wrap the operation in Try and handle the failure in Catch; statements after the failure in Try are skipped. section 15.4
- Capture details with -ErrorVariable when the response depends on which exception occurred. section 15.5
- Use typed Catch blocks for different .NET exception types and Finally for cleanup or follow-up work that must always run. section 15.7
Retrying a failed computer connection
A machine-information tool connects to one computer at a time with New-CimSession. It stops that command on failure, catches the exception, warns the user, and optionally retries with the alternate protocol. Handling one computer per iteration prevents one failure from abandoning the remaining computers. section 15.4
Try {
# something here generates an exception
} Catch [Exception.Type.One] {
# deal with that exception here
} Catch [Exception.Type.Two] {
# deal with the other exception here
} Catch {
# deal with anything else here
} Finally {
# run something else
}
Use the Try/Catch/Finally pattern as a reusable template for typed and general exception handling. section 15.7
























