How to stop a PowerShell script on the first error?

后端 未结 8 1769
长情又很酷
长情又很酷 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 06:59

    A slight modification to the answer from @alastairtree:

    function Invoke-Call {
        param (
            [scriptblock]$ScriptBlock,
            [string]$ErrorAction = $ErrorActionPreference
        )
        & @ScriptBlock
        if (($lastexitcode -ne 0) -and $ErrorAction -eq "Stop") {
            exit $lastexitcode
        }
    }
    
    Invoke-Call -ScriptBlock { dotnet build . } -ErrorAction Stop
    

    The key differences here are:

    1. it uses the Verb-Noun (mimicing Invoke-Command)
    2. implies that it uses the call operator under the covers
    3. mimics -ErrorAction behavior from built in cmdlets
    4. exits with same exit code rather than throwing exception with new message
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题