你能捕捉错误代码和异常信息抛出使用Powershell调用c#控制台应用程序

本文关键字:Powershell 调用 应用程序 控制台 错误代码 信息 异常 | 更新日期: 2023-09-27 18:05:43

我有一个powershell脚本,它监视要放入其中的数据文件的文件夹。当它看到一个文件时,它就开始通过调用我用c#编写的控制台应用程序来处理它。现在,我可以返回一个错误代码并确定任务是否失败。如果失败,它会发送一封电子邮件。我想知道的是,如果我可以返回一个int错误代码和在堆栈上抛出的异常,这样当powershell获得错误代码时,它也可以将在我的c#应用程序中发生的异常添加到它发出的电子邮件中。我现在收到了电子邮件,然后不得不去查看一个日志文件,c#应用程序将所有异常处理写入其中。这是可能的,还是我唯一的选择是编写不同的int值,这意味着每个异常,然后在我的powershell脚本中进行case选择,以获得导致失败的实际错误是什么?

提前感谢。

而不是通过电子邮件发送"文件失败....."并获得退出代码0或更大,我还可以收到实际导致powershell脚本错误的异常吗?

下面的Powershell代码的简短示例,其中一些代码出于某些目的被删除:

==================================================================================

  $emailFrom = e@example.com"
  $emailTo = "me@example.com"
  $emailSubject = "Overlay File Processing Failed"
  $emailBody = ""
  $fileCtr = 0
  $logPath = "E:'path to log file"
  Add-Content -Path $logPath -Value "[$([DateTime]::Now)] Checking for files."
  if ($fileCtr -gt 0) 
  {
      Add-Content -Path $logPath -Value "[$([DateTime]::Now)] Found $fileCtr files to process."
ForEach ($_Name in $pdffiles) 
{
   $fullfile = $pdfdir + $_Name
   $StartProc = Start-Process F:'my C# .exe -ArgumentList "$fullfile $outdir" -RedirectStandardOutput "e:'my C# app log.txt"-Wait -PassThru
   $exCode = $StartProc.ExitCode
   if ($StartProc.ExitCode -ne 0) 
    {
        Get-Content -Path e:'log.txt
        $emailBody = "processing failed for file " + $pdfdir + $_Name
        send-mailmessage -from $emailFrom -to $emailTo -subject $emailSubject -body $emailBody -smtpServer $emailServer
    Add-Content -Path $logPath -Value "[$([DateTime]::Now)] Processing failed for file $fullfile. Exit Code:$exCode" 
        $fileparts =  $_Name.ToString().split(".")
        move-item $fullfile ($fileparts[0] + "{0:yyyyMMddhhmmss}.pdf" -f (get-date))
        } else {
        Add-Content -Path $logPath -Value "[$([DateTime]::Now)] Processing succesfull for file $fullfile"
        $fileparts =  $_Name.ToString().split(".")
        move-item $fullfile ($fileparts[0] + "_{0:yyyyMMddhhmmss}.pdf" -f (get-date))
    }
}
} else {
   Add-Content -Path $logPath -Value "[$([DateTime]::Now)] No files to process."
}

你能捕捉错误代码和异常信息抛出使用Powershell调用c#控制台应用程序

我找到了问题的答案。你不能做我想做的事。可以采取的方法是从控制台应用程序写入日志文件,然后从powershell脚本读取它,或者只是使用代表某些失败的特定int值,并通过它们切换以报告相应的错误。