尝试在Powershell中捕获可执行文件exe?

JBu*_*ace 13 powershell try-catch

我想在Powershell中对.exe执行Try Catch,我看起来像这样:

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

echo "DONE: "
echo $output
Run Code Online (Sandbox Code Playgroud)

当我使用说无效的域时,它会返回一个错误,psftp.exe : Fatal: Network error: Connection refused但我的代码没有捕获它.

我怎么会发现错误?

Kei*_*ill 21

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
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我必须说,就我而言,我有一个可执行文件,为了测试建议,我在代码开头抛出异常,当我的 powershell 脚本运行时,由于异常而出现一个弹出窗口,我必须单击按钮才能继续。这里的要点是, if 语句和 try catch 块上都不会捕获异常。 (2认同)

小智 10

> 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
Run Code Online (Sandbox Code Playgroud)