Last active
September 19, 2016 16:42
-
-
Save schwartzmx/d1f029ed3a7a05b40e8e091462869685 to your computer and use it in GitHub Desktop.
Intended only to be run as a scheduled job on a SQL Server. This should be scheduled every $LogTimeSpanMinutes as a SQL Agent job. This grabs the events logs and emails on Error level logs being found and shoots an email with the contents of the errors.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$LogTimeSpanMinutes = 10 | |
$AfterDate = (Get-Date).AddMinutes(-$LogTimeSpanMinutes) | |
$SQLMailProfile = "DoNotReplyNotification" | |
$recipients = "[email protected]" | |
$subject = "Failover Cluster ERRORS" | |
$body = "<!DOCTYPE html><html><head></head><br><body> {0} </body></html>" | |
$LocalServer = hostname | |
Function DBA-SendMail { | |
param( | |
[String]$Message | |
) | |
$emailBody = $body -f $Message | |
$sendMailQuery = " | |
EXEC [msdb].dbo.sp_send_dbmail | |
@profile_name='${SQLMailProfile}', | |
@recipients='${recipients}', | |
@subject='${subject}', | |
@body='${emailBody}', | |
@body_format='HTML' | |
GO | |
" | |
Try { | |
$mailQuery = $sendMailQuery | |
Invoke-SqlCmd -Query "$mailQuery" -ServerInstance "(local)" -HostName "$LocalServer" -QueryTimeout 0 -ConnectionTimeout 0 | out-null | |
} | |
Catch { | |
$ex = $_.Exception | |
Write-Error "$ex.Message" | |
Throw "Failure" | |
Exit 1 | |
} | |
} | |
Try { | |
$logs = Get-EventLog -LogName System -Source Microsoft-Windows-FailoverClustering -After $AfterDate -ErrorAction Stop | |
} | |
Catch { | |
If ($_ -like '*No matches found*') { | |
Write-Output "Exiting gracefully, no logs found!" | |
} | |
Else { | |
Throw "Error: $_" | |
Exit 1 | |
} | |
} | |
$errs = $logs | ? { $_.EntryType -eq "Error"} | |
$msg = "" | |
If ($errs.Count -gt 0) { | |
ForEach ($e in $errs) { | |
$t = $e.TimeGenerated | |
$et = $e.EntryType.ToString().ToUpper() | |
$i = $e.InstanceID | |
$m = $e.Message | |
$msg += "["+ $t +"] " + $et + " - " + $i + " - " + $m + "`r`n" | |
} | |
DBA-SendMail -Message $msg | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment