从PowerShell中的C#应用​​程序查询抛出的异常

时间:2016-10-17 15:23:00

标签: c# powershell exception-handling powershell-v3.0

我正在PowerShell中运行应用程序,如下所示:

$exe = "C:\blah\build\blah\Release\blahblah.exe"
&$exe scheduledRun sliceBicUp useEditionId

blahblah.exe是一个C#.NET 4.5控制台应用程序。现在我知道这个可执行文件可能会抛出错误等。我可以在PowerShell脚本本身中捕获这些错误/异常吗?

基本上我希望PowerShell脚本能够检测到发生的错误/异常并采取行动,比如给我们的帮助台发送电子邮件。

2 个答案:

答案 0 :(得分:2)

@Liam所述,来自外部程序的错误不是例外。如果可执行文件以正确的退出代码终止,您可以检查automatic variable $LastExitCode并对其值作出反应:

& $exe scheduledRun sliceBicUp useEditionId
switch ($LastExitCode) {
  0 { 'success' }
  1 { 'error A' }
  2 { 'error B' }
  default { 'catchall' }
}

您可以做的唯一其他事情是解析output以获取错误消息:

$output = &$exe scheduledRun sliceBicUp useEditionId *>&1
if ($output -like '*some error message*') {
  'error XY occurred'
}

答案 1 :(得分:0)

您可以使用此代码。当.Net程序退出时,错误将传递给ps脚本

ConstantAsMetadata