【问题标题】:Handle errors of external programs处理外部程序的错误
【发布时间】:2017-12-03 19:22:59
【问题描述】:

我正在编写一个执行外部程序和其他脚本的 PowerShell 脚本。

我在主脚本中调用 .exe 和 .ps1 脚本如下:

& ./directory/file.exe

or

& ./directory/script.ps1

如何捕捉错误?

它像 unix,我可以使用 $? 并做类似的事情:

if($? -ne 0) then exit 1 ...

这是最好的方法吗? 我们可以在 PowerShell 中使用 EXIT 吗?

顺便问一下,使用“&”是调用 .exe 文件的最佳方式吗? .ps1 ?

【问题讨论】:

    标签: windows powershell error-handling


    【解决方案1】:
    powershell中的

    $?是布尔值,只反映前一个powershell语句的执行状态。

    对于外部程序,检查$LASTEXITCODE:

    & .\directory\file.exe 
    if($LASTEXITCODE){
        return 
    }
    

    在上面的示例中,我使用return - exit 也可以,但我通常避免使用exit,因为它会指示主机应用程序立即退出,如果您这样做可能会也可能不会想要从另一个脚本调用您的脚本,作为未来更大操作的一部分。

    调用运算符& 可以完美地处理可执行文件和powershell 脚本文件路径。

    【讨论】:

    • exit 在脚本内只会退出该脚本而不是整个主机。
    • 看起来它不适用于 $LastExitCode。我故意让mail.exe 失败。在下面使用时,即使 email.exe 失败,返回码也是 0。 $LastExitCode 的值为 0。 & mail.exe email -el $eml -smt $smtp_server if($LastExitCode > 0) { write-host "Error sent email" exit 5 } write-host "Email success" when using below , 有用。 & mail.exe email -el $eml -smt $smtp_server if(!$?) { write-host "Error sent email" exit 5 } write-host "Email success" 我不明白为什么
    • @Linus 将 $LastExitCode > 0 更改为 $LastExitCode -gt 0 - > 是流重定向运算符
    • 即使使用 -gt 0 也无法正常工作。我将使用 $?,这是我捕获错误的唯一方法
    猜你喜欢
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    相关资源
    最近更新 更多