Sunday, 15 March 2015

Powershell - Email last 10 failed entries

Import-Module SQLPS -DisableNameChecking  
#current server name 
$servername = "ROGUE" # or localhost  
$server = New-Object "Microsoft.SqlServer.Management.Smo.Server" $servername  

#get the last 10 error entries, and convert to HTML  
$content = ($server.ReadErrorLog() | Where-Object {$_.Text -like "*failed*" -or $_.Text -like "*error*" -or $_.HasErrors -eq $true} |  
Select-Object LogDate, ProcessInfo, Text, HasErrors -Last 10 | ConvertTo-Html)  

#email settings  
$currdate = Get-Date -Format "yyyy-MM-dd hmmtt"  
$smtp = "mail.rogue.local"
$to = "DBA <administrator@rogue.local>"  
$from = "DBMail <dbmail@administrator.local>"
$subject = "Last 10 Errors as of $currdate"

 #send the email  
Send-MailMessage -SmtpServer $smtp -To $to -from $from -Subject $subject -Body "$($content)" -BodyAsHtml

No comments:

Post a Comment