Catching errors
Capturing an error so that a script can react to it depends on the error type:
- Non-terminating errors can be captured by using the
ErrorVariableparameter. - Terminating errors can be captured by using either a
try,catch, andfinallystatement, or by using atrapstatement.
Although trap can be used to handle terminating errors, exploring trap is deferred until later in this chapter because it is infrequently used for that task.
The ErrorVariable parameter can be used to create a scoped alternative to the Error variable.
ErrorVariable
The Error variable is a collection (ArrayList) of handled and unhandled errors raised in the PowerShell session.
The ErrorVariable parameter can be used to name a specific variable that should be used for a command. The ErrorVariable accepts the name of a variable and is created as an ArrayList.
The following function writes a single error using the Write-Error command:
function Invoke...