我有一个PowerShell脚本,它监视一个文件夹以便数据文件被放入其中。当它发现有文件时,它会调用我的用C#编写的控制台应用程序来处理它。现在,我可以返回错误代码并确定作业是否失败。如果失败,就会发送一封电子邮件。我想知道的是,我是否可以返回一个整数错误代码和堆栈上抛出的异常,这样当PowerShell获取错误代码时,它也可以将在我的C#应用程序中发生的异常添加到发送的电子邮件中。目前,我会收到电子邮件,然后不得不查看C#应用程序写入所有异常处理的日志文件。这种做法可行吗?或者我的唯一选择是编写不同的整数值表示每个异常,并在我的PowerShell脚本内使用case选择语句以获取导致失败的实际错误?
提前感谢您。
与其仅通过电子邮件发送“文件失败……”并获取大于0的退出代码,不如在PowerShell脚本中同时接收实际导致错误的异常。
以下是PowerShell代码的简短示例,为了某些目的而省略了某些代码:
==================================================================================
提前感谢您。
与其仅通过电子邮件发送“文件失败……”并获取大于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."
}