Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a PowerShell script on the first error?

I want my PowerShell script to stop when any of the commands I run fail (like set -e in bash). I'm using both Powershell commands (New-Object System.Net.WebClient) and programs (.\setup.exe).

like image 268
Andres Riofrio Avatar asked Mar 30 '12 18:03

Andres Riofrio


People also ask

How do you break a loop in PowerShell?

If you use the break keyword with a label, PowerShell exits the labeled loop instead of exiting the current loop. The label is a colon followed by a name that you assign. The label must be the first token in a statement, and it must be followed by the looping keyword, such as while .

How do I stop a PowerShell script from running in the background?

You can use Stop-Job to stop background jobs, such as those that were started by using the Start-Job cmdlet or the AsJob parameter of any cmdlet. When you stop a background job, PowerShell completes all tasks that are pending in that job queue and then ends the job.


2 Answers

$ErrorActionPreference = "Stop" will get you part of the way there (i.e. this works great for cmdlets).

However for EXEs you're going to need to check $LastExitCode yourself after every exe invocation and determine whether that failed or not. Unfortunately I don't think PowerShell can help here because on Windows, EXEs aren't terribly consistent on what constitutes a "success" or "failure" exit code. Most follow the UNIX standard of 0 indicating success but not all do. Check out the CheckLastExitCode function in this blog post. You might find it useful.

like image 185
Keith Hill Avatar answered Sep 22 '22 02:09

Keith Hill


You should be able to accomplish this by using the statement $ErrorActionPreference = "Stop" at the beginning of your scripts.

The default setting of $ErrorActionPreference is Continue, which is why you are seeing your scripts keep going after errors occur.

like image 41
goric Avatar answered Sep 25 '22 02:09

goric