How to stop a PowerShell script on the first error?

后端 未结 8 1777
长情又很酷
长情又很酷 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

提交回复
热议问题