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
).
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 .
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.
$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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With