Friday, June 18, 2010

Try Catch template for Powershell

Try Catch template
try
{
try
{
# Command that uses -erroraction stop or $erroractionpreference = 'Stop'
}
# Here we catch the Exception generated by the ErrorAction "Stop"
# Only necessary if there is any processing we want to do if the
# exception is of type ActionPreferenceStopExecution,
# otherwise this block can be deleted
catch [System.Management.Automation.ActionPreferenceStopException]
{
# Error Handling specific to ActionPreferenceStopException goes here
# Rethrow the "real" exception as a terminating error
Throw $_.exception
}
# All errors are caught and rethrown to the outer try/catch block
# as terminating errors to be handled.
catch
{
Throw $_.exception
}
}
# Here we can resume exception type handling as usual
catch #[System.Management.Automation.ItemNotFoundException]
{
"Got it!"
}

No comments: