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 (...)条件.
小智 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)
| 归档时间: |
|
| 查看次数: |
10195 次 |
| 最近记录: |