【问题标题】:Try Catch on executable exe in Powershell?尝试在 Powershell 中捕获可执行 exe?
【发布时间】:2012-09-03 18:38:06
【问题描述】:

我想在 Powershell 中对一个 .exe 执行 Try Catch,我的结果如下所示:

Try
{
    $output = C:\psftp.exe ftp.blah.com 2>&1
}
Catch
{
    echo "ERROR: "
    echo $output
    return
}

echo "DONE: "
echo $output

当我使用无效域时,它会返回类似 psftp.exe : Fatal: Network error: Connection refused 的错误,但我的代码没有捕捉到。

如何发现错误?

【问题讨论】:

    标签: powershell try-catch


    【解决方案1】:

    > PowerShell 中的 try / catch 不适用于本机可执行文件。

    实际上确实如此,但前提是您使用“$ErrorActionPreference = 'Stop'”并附加“2>&1”。

    请参阅“处理本机命令”/Tobias Weltner,https://community.idera.com/database-tools/powershell/powertips/b/ebookv2/posts/chapter-11-error-handling

    例如

    $ErrorActionPreference = 'Stop'
    Try
    {
        $output = C:\psftp.exe ftp.blah.com 2>&1
    }
    Catch
    {
        echo "ERROR: "
        echo $output
        return
    }
    echo "DONE: "
    echo $output
    

    【讨论】:

      【解决方案2】:

      try / catch 在 PowerShell 中不适用于本机可执行文件。调用 psftp.exe 后,检查自动变量 $LastExitCode。这将包含 psftp 的退出代码,例如:

      $output = C:\psftp.exe ftp.blah.com 2>&1
      if ($LastExitCode -ne 0)
      {
          echo "ERROR: "
          echo $output
          return
      }
      

      上面的脚本假定 exe 在成功时返回 0,否则返回非零。如果不是这种情况,请相应地调整if (...) 条件。

      【讨论】:

      • 我必须说,在我的情况下,我有一个可执行文件,对于测试建议,我在代码的开头抛出一个异常,当我的 powershell 脚本运行时,由于异常和我必须单击按钮才能继续。这里的重点是 if 语句和 try catch 块都没有捕获到异常。
      猜你喜欢
      • 1970-01-01
      • 2020-04-21
      • 2016-11-22
      • 1970-01-01
      • 2019-04-17
      • 2010-10-29
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多