Skip to content

Instantly share code, notes, and snippets.

@schwartzmx
Last active September 19, 2016 16:42
Show Gist options
  • Save schwartzmx/d1f029ed3a7a05b40e8e091462869685 to your computer and use it in GitHub Desktop.
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.
$LogTimeSpanMinutes = 10
$AfterDate = (Get-Date).AddMinutes(-$LogTimeSpanMinutes)
$SQLMailProfile = "DoNotReplyNotification"
$recipients = "email@gmail.com"
$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