I am using a PowerShell script that completes 5 different interdependent tasks sequentially. I want the script to stop execution as soon as it hits a catch block and send an email. Also, this script executes a console app. How do I stop execution of the PowerShell script in case of a console exception? I am logging console exceptions using the -RedirectStandardError parameter.
Add a comment
|
1 Answer
Stopping execution in the catch block is accomplished by using the Break keyword, this should be added last, e.g.:
Catch
{
Send-MailMessage -From [email protected] -To [email protected] -Subject "HR File Read Failed!" -SmtpServer EXCH01.AD.MyCompany.Com
Break
}
If you want to catch non-terminating errors as well, you'll need:
-ErrorAction Stop
at the end of your commandlet (or set it as a preference / session setting)
1 Comment
ADTC
-ErrorAction is unrecognized in Powershell version 5.1.14393.953.. or Am I doing something wrong?: cat script.ps1 | powershell -ErrorAction Stop -command - (It also didn't recognize $ErrorActionPreference = "Stop")