13

我想在 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但我的代码没有捕捉到它。

我将如何捕捉错误?

4

2 回答 2

26

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 (...)相应地调整条件。

于 2012-09-10T21:12:58.697 回答
5

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

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

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

例如

$ErrorActionPreference = 'Stop'
Try
{
    $output = C:\psftp.exe ftp.blah.com 2>&1
}
Catch
{
    echo "ERROR: "
    echo $output
    return
}
echo "DONE: "
echo $output
于 2020-05-08T07:42:51.943 回答