How to stop a PowerShell script on the first error?

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

    Redirecting stderr to stdout seems to also do the trick without any other commands/scriptblock wrappers although I can't find an explanation why it works that way..

    # test.ps1
    
    $ErrorActionPreference = "Stop"
    
    aws s3 ls s3://xxx
    echo "==> pass"
    
    aws s3 ls s3://xxx 2>&1
    echo "shouldn't be here"
    

    This will output the following as expected (the command aws s3 ... returns $LASTEXITCODE = 255)

    PS> .\test.ps1
    
    An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied
    ==> pass
    

提交回复
热议问题