在 PowerShell 中查询 C# 应用抛出的异常

Query a thrown exception from a C# App in PowerShell

我是 运行 PowerShell 中的一个应用,如下所示:

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

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

基本上我希望 PowerShell 脚本检测到 error/exception 已经发生并采取行动,例如给我们的帮助台发送电子邮件。

As mentioned, errors from external programs are not exceptions. If the executable terminates with a proper exit code you could check the 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'
}

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

   $exe = "C:\Users\johnn\OneDrive\Documents\visual studio 2015\Projects\test\test\bin\Release\test.exe"

   $pinfo = New-Object System.Diagnostics.ProcessStartInfo
   $pinfo.FileName = $exe
   $pinfo.RedirectStandardError = $true
   $pinfo.RedirectStandardOutput = $true
   $pinfo.UseShellExecute = $false
   $pinfo.Arguments = "localhost"
   $p = New-Object System.Diagnostics.Process
   $p.StartInfo = $pinfo
   $p.Start() | Out-Null
   $p.WaitForExit()
   $stdout = $p.StandardOutput.ReadToEnd()
   $stderr = $p.StandardError.ReadToEnd()
   Write-Host "stdout: $stdout"
   Write-Host "stderr: $stderr"
   Write-Host "exit code: " + $p.ExitCode