0

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.

1 Answer 1

2

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)

https://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell

Sign up to request clarification or add additional context in comments.

1 Comment

-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")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.