Catching errors
Capturing an error so that a script can react to that error depends on the error type.
- Non-terminating errors can be captured by using
ErrorVariable
- Terminating errors can be captured using either a
try
,catch
, andfinally
statement, or by using atrap
statement
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.
You can use the -ErrorVariable
parameter to name a variable that should be used for a specific script. 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-Something {
[CmdletBinding()]
param ( )
Write-Error 'Invoke-Something Failed'
}
The command can be run using the -ErrorVariable
parameter...