How to stop a PowerShell script on the first error?

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

    I came here looking for the same thing. $ErrorActionPreference="Stop" kills my shell immediately when I'd rather see the error message (pause) before it terminates. Falling back on my batch sensibilities:

    IF %ERRORLEVEL% NEQ 0 pause & GOTO EOF
    

    I found that this works pretty much the same for my particular ps1 script:

    Import-PSSession $Session
    If ($? -ne "True") {Pause; Exit}
    

提交回复
热议问题