How to stop a PowerShell script on the first error?

后端 未结 8 1776
长情又很酷
长情又很酷 2020-12-02 06:11

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.

8条回答
  •  春和景丽
    2020-12-02 07:00

    $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.

提交回复
热议问题