你能使用Powershell调用C#控制台应用程序并捕获错误代码和异常信息吗?

3
我有一个PowerShell脚本,它监视一个文件夹以便数据文件被放入其中。当它发现有文件时,它会调用我的用C#编写的控制台应用程序来处理它。现在,我可以返回错误代码并确定作业是否失败。如果失败,就会发送一封电子邮件。我想知道的是,我是否可以返回一个整数错误代码和堆栈上抛出的异常,这样当PowerShell获取错误代码时,它也可以将在我的C#应用程序中发生的异常添加到发送的电子邮件中。目前,我会收到电子邮件,然后不得不查看C#应用程序写入所有异常处理的日志文件。这种做法可行吗?或者我的唯一选择是编写不同的整数值表示每个异常,并在我的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."
}
1个回答

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

2
或者,由于您使用C#编写了控制台应用程序,您可能可以相对容易地将其转换为类库,然后在PowerShell进程中使用它。 - OldFart
我没有想到那个。这有什么好处?那样的话,我就可以做我想做的事情了,不是吗???? - Casey ScriptFu Pharr
是的,你可以在PowerShell中捕获异常。 - OldFart
请问您如何做到这一点?我已经到处搜索了。我知道Windows环境使用全局变量中的最后一个异常,但我需要该异常被PowerShell脚本捕获并执行我的程序。由于必须具有类型为int或void的Main[args],那么我该如何将其发送回PowerShell代码呢?-感谢@OldFart。 - Casey ScriptFu Pharr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接