1

Does anyone have a PowerShell script to query results from a SQL Server database and send it out as an email in HTML format?

1 Answer 1

2

Following is a script I use to send query results in an HTML-formatted email. Basically pipe the result of invoke-sqlcmd to ConvertTo-Html and then to Out-String, and then massage it a bit to get the table to display nicely. If you don't add the padding style, everything will run together.

Send-MailMessage example below is for unathenticated, so if you have to authenticate to your SMTP server you'll need to fix that up

$Alerts = invoke-sqlcmd -ServerInstance dbserver -Database dbname -Query "SELECT * FROM some_table" | SELECT Severity, ServerName, Heading | ConvertTo-Html | Out-String
$Alerts = $Alerts.Replace("</head>", "<style> TD {padding-left: 2mm}</style></head>")
Send-MailMessage -To [email protected] -From [email protected] -BodyAsHtml $Alerts -Subject "Alerts" -SmtpServer "smtp.mycompany.com"
1
  • Thank you so much Tony for that input, that was exactly what i was looking for appreciate it! Commented May 7, 2020 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.