Powershell analogue of Bash's `set -e`

前端 未结 1 1042
被撕碎了的回忆
被撕碎了的回忆 2021-02-20 14:38

How can I make Powershell behave like Bash with its flag set -e? set -o errexit makes a Bash script \"Exit immediately if a simple command exits with a

相关标签:
1条回答
  • 2021-02-20 14:56

    $ErrorActionPreference works as intended, it's just that exit codes from native programs are not nearly as well-behaved as PowerShell cmdlets.

    For a cmdlet the error condition is fairly easy to determine: Did an exception happen or not? So the following would not reach the Write-Host statement with $ErrorActionPreference set to Stop:

    Write-Error blah
    

    or

    Get-ChildItem somepathwhichsurelydoesntexisthere
    

    For native programs an exit code of zero usually signals that no error occurred but that's merely a convention, as is a non-zero exit code signalling an error. Would you say that if choice exists with an exit code of 1 that it was an error?

    The only robust way to handle this is to check the exit code after running a native command and handling it yourself, if needed. PowerShell doesn't try to guess what the result meant because the conventions aren't strong enough to warrant a default behaviour in this case.

    You can use a function if you want to make your life easier:

    function Invoke-NativeCommand {
      $command = $args[0]
      $arguments = $args[1..($args.Length)]
      & $command @arguments
      if (!$?) {
        Write-Error "Exit code $LastExitCode while running $command $arguments"
      }
    }
    

    But in general many programs need different handling because they don't adhere to said convention.

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