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

本文关键字:异常 应用 PowerShell 查询 | 更新日期: 2023-09-27 18:13:35

我在PowerShell中运行一个应用程序,像这样:

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

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

基本上我希望PowerShell脚本检测错误/异常已经发生,并采取行动,如电子邮件我们的帮助台,例如。

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

正如@Liam所提到的,来自外部程序的错误也不例外。如果可执行文件以正确的退出代码结束,您可以检查自动变量$LastExitCode并对其值作出反应:

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

您可以做的唯一一件事是解析错误消息的输出:

$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