Deepanshu Kalra
Deepanshu Kalra

Reputation: 459

How to break powershell script execution on first error?

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.

Upvotes: 0

Views: 4492

Answers (1)

SLWS
SLWS

Reputation: 546

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

Upvotes: 2

Related Questions