How to stop a PowerShell script on the first error?

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

    Sadly, due to buggy cmdlets like New-RegKey and Clear-Disk, none of these answers are enough. I've currently settled on the following code in a file called ps_support.ps1:

    Set-StrictMode -Version Latest
    $ErrorActionPreference = "Stop"
    $PSDefaultParameterValues['*:ErrorAction']='Stop'
    function ThrowOnNativeFailure {
        if (-not $?)
        {
            throw 'Native Failure'
        }
    }
    

    Then in any powershell file, after the CmdletBinding and Param for the file (if present), I have the following:

    $ErrorActionPreference = "Stop"
    . "$PSScriptRoot\ps_support.ps1"
    

    The duplicated ErrorActionPreference = "Stop" line is intentional. If I've goofed and somehow gotten the path to ps_support.ps1 wrong, that needs to not silently fail!

    I keep ps_support.ps1 in a common location for my repo/workspace, so the path to it for the dot-sourcing may change depending on where the current .ps1 file is.

    Any native call gets this treatment:

    native_call.exe
    ThrowOnNativeFailure
    

    Having that file to dot-source has helped me maintain my sanity while writing powershell scripts. :-)

提交回复
热议问题