Inspecting and rethrowing PowerShell errors
Inspect PowerShell errors ($Error, call stack) and rethrow exceptions with context.
A few commands and settings that help you analyse a PowerShell error and control how a script reacts to it.
Inspecting the last error
Get-PSCallStack
$Error[0].Exception.StackTrace
$Error[0].Exception.InnerException.StackTrace
$Error[0].StackTrace
$Error[0] | Format-List -Force
$Error[0] | Select-Object *
$Error is a collection holding the errors of the session; the most recent error is $Error[0].
Rethrowing an exception with context
} catch {
Write-JobStatus -Id $rowID -Status "error" -ErrorMessage $_ -Ended (Get-Date)
throw ( New-Object System.Exception( "New Exception", $_.Exception ) )
Throw $_.Exception
}
The Throw $_.Exception line placed after throw is never reached, because the first throw ends the catch block.
Debug mode
Shows information, verbose and debug messages, and stops the script on the first error.
$ErrorActionPreference = 'Stop'
$InformationPreference = 'Continue'
$VerbosePreference = 'Continue'
$DebugPreference = 'Continue'
Back to default behaviour
$ErrorActionPreference = 'Continue'
$InformationPreference = 'SilentlyContinue'
$VerbosePreference = 'SilentlyContinue'
$DebugPreference = 'SilentlyContinue'
For a related SMO example, see sqlserverpowershell.com.