使用Try Catch记录错误,即使发生错误也希望发送摘要电子邮件

时间:2015-11-12 21:08:03

标签: powershell

我希望这不是一个"你不能吃蛋糕而且吃得太多了#34;场景。

目前:

脚本运行,对sources.csv中的所有对象执行try / catch,为每个失败的对象生成错误日志。除非所有对象都成功,否则不发送电子邮件。

尝试:

脚本运行,对sources.csv中的所有对象执行try / catch,为每个失败的对象生成错误日志。发送电子邮件,显示发生了多少错误并附加所有相关日志文件。

$clientID = "Blargh Inc"
$intelDir = "C:\Threat Intelligence"
$webclient = New-Object System.Net.WebClient
$intelSource = "$($intelDir)\sources.csv"
$intelCount = 0
$intelError = 0

# Begin Email Options
$body = "Threat Intelligence Feed ran for $clientID - "
$subject = "$($clientID) - Threat Intelligence - "
$email = @{
From = "me@mycompany.com"
To = "me@mycompany.com","notme@mycompany.com"
Subject = $subject
SMTPServer = "mail-server.office365.com"
Body = $body
}
# End Email Options

import-Csv $intelSource -ErrorAction SilentlyContinue | ForEach-Object {
        $storageDir = "$($intelDir)\$($_.threatType) $($_.threatSubtype)"
        $threat = $_.threatType + "_" + $_.threatSubtype    # Set this variable to save headaches passing it later
        $storageFile = "$($storageDir)\$($threat)_$($(get-date -f MM-dd-yy)).csv"    # Filename specified by sources.csv fields and today's date
        $url = $_.threatLocation
        # Begin Error Logging
        try {
            $intelCount++
            $webclient.DownloadFile($url,$storageFile)
        }
        catch {
            $intelError++
            $intelErrorMessage = $_.Exception|format-list -force
            echo $intelErrorMessage | Out-File $intelDir\$threat"_ErrorLog_"$(get-date -f MM-dd-yy).txt -Append
            Continue
        }
        # End Error Logging
        # Cleanup
        finally {
            $webclient.Dispose()
        }
        # Throttling (mainly future use with multiple sources)
        Start-Sleep 5
        }

发生错误时未处理的部分:

if ($intelError -gt 0) {
    $email.Item('Subject') += "$($intelError) Error(s)"
    $email.Item('Body') += "$($intelError) of $($intelCount) sources failed. See attached error log(s)"
    Get-ChildItem -Path $intelDir | Where {$_.Name -match "$($(get-date -f MM-dd-yy))"} | foreach{$_.fullname} | Send-MailMessage @email
}
else {
    $email.Item('Subject') += "Success"
    $email.Item('Body') += "No errors"
    Send-MailMessage @email
}

1 个答案:

答案 0 :(得分:0)

评论后添加:

将您现有的代码包含在另一个try / finally块中,然后将电子邮件代码放入 finally块中:

try {
    import-Csv $intelSource -ErrorAction SilentlyContinue | ForEach-Object {
            $storageDir = "$($intelDir)\$($_.threatType) $($_.threatSubtype)"
            $threat = $_.threatType + "_" + $_.threatSubtype    # Set this variable to save headaches passing it later
            $storageFile = "$($storageDir)\$($threat)_$($(get-date -f MM-dd-yy)).csv"    # Filename specified by sources.csv fields and today's date
            $url = $_.threatLocation
            # Begin Error Logging
            try {
                $intelCount++
                $webclient.DownloadFile($url,$storageFile)
            }
            catch {
                $intelError++
                $intelErrorMessage = $_.Exception|format-list -force
                echo $intelErrorMessage | Out-File $intelDir\$threat"_ErrorLog_"$(get-date -f MM-dd-yy).txt -Append
                Continue
            }
            # End Error Logging
            # Cleanup
            finally {
                $webclient.Dispose()
            }
            # Throttling (mainly future use with multiple sources)
            Start-Sleep 5
            }
} finally {
    # email code
}

将电子邮件发送部分添加到finally {}块。该块的重点是始终在那里运行代码,即使触发了catch {}块,即使发生了catch块没有捕获的异常。