PowerShell For DBA Part-8 (Write PowerShell output in email body or send as attachment)

Watch Part-1Part-2Part-3Part-4Part-5, Part-6, Part-7

Send the output as email body


Get-Credential "YourEmail@gmail.com"|Export-Clixml D:\PowerShell\Cred.txt
$credential=Import-Clixml D:\PowerShell\Cred.txt

$Header = @"
<style>
TABLE {border-width: 1px; border-style: solid; border-color: black; border-collapse: collapse;}
TH {border-width: 1px; padding: 3px; border-style: solid; border-color: black; background-color: #9999CC;}
TD {border-width: 1px; padding: 3px; border-style: solid; border-color: black;}
</style>
"@

Get-DbaAgentJob -SQLinstance localhost,Localhost\SQL2017|
Select Computername,Name,CurrentRunStatus,LastRunOutcome | ConvertTo-Html -body "<H2> Agent Job Report</H2>"-Head $Header |Out-File D:\PowerShell\AgentJob.html

$JobReport = [System.IO.File]::ReadAllText('D:\PowerShell\AgentJob.html')
$body= "<p>Below is Agent jobs status</p>"+" $JobReport "

$Email="YourEmail@gmail.com"
$SMTP="SMTP.Gmail.com"
$TO="YourEmail@yahoo.com"
$Subject="Agent Job Alert"

Send-MailMessage -Body $body -BodyAsHtml -From $Email -SmtpServer $SMTP -Subject $Subject -To $TO -Credential $Credential -Usessl -Port 587


Send the output as attachment


Get-Credential "YourEmail@gmail.com"|Export-Clixml D:\PowerShell\Cred.txt
$credential=Import-Clixml D:\PowerShell\Cred.txt

$Header = @"
<style>
TABLE {border-width: 1px; border-style: solid; border-color: black; border-collapse: collapse;}
TH {border-width: 1px; padding: 3px; border-style: solid; border-color: black; background-color: #9999CC;}
TD {border-width: 1px; padding: 3px; border-style: solid; border-color: black;}
</style>
"@

Get-DbaAgentJob -SQLinstance localhost|
Select Computername,Name,CurrentRunStatus,LastRunOutcome | ConvertTo-Html -body "<H2> Agent Job Report</H2>"-Head $Header |Out-File D:\PowerShell\AgentJob.html

$body= "<p>Agent jobs report attached</p>"

$Email="YourEmail@gmail.com"
$SMTP="SMTP.Gmail.com"
$TO="YourEmail@yahoo.com"
$Subject="Agent Job Alert"

Send-MailMessage -Body $body -BodyAsHtml -Attachment D:\PowerShell\AgentJob.html -From $Email -SmtpServer $SMTP -Subject $Subject -To $TO -Credential $Credential -Usessl -Port 587


Follow me:

Blog: http://Sqldepository.com

YouTube : Sql depository

Facebook: https://www.facebook.com/sqldepository/

Google+ :https://plus.google.com/u/0/107093915534620159617

 

Author: Sauras Pandey

Sauras Pandey is an MCP, SQL Server DBA/Architect with 9+ years of experience working in a variety of environments

Leave a Reply

Your email address will not be published.