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
).
Windows – How to stop a PowerShell script on the first error
powershellwindows
Related Topic
- Powershell – Terminating a script in PowerShell
- Windows – How to run a PowerShell script
- Windows – How to output something in PowerShell
- PowerShell says “execution of scripts is disabled on this system.”
- Powershell – What’s the best way to determine the location of the current PowerShell script
- Powershell – In PowerShell, how to define a function in a file and call it from the PowerShell commandline
- Java – Can’t start Eclipse – Java was started but returned exit code=13
- Windows – Filename too long in Git for Windows
Best Answer
$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.