Hi All,
I have a powershell script which executes a SQL Query on three SQL instances and provides the result in table format through email. The output email contains all the result of the query in a single output itself. Please help me, I have provided the code which I am using
Sample output format which I am getting:
ServerInstance DatabasenameEnabledStatus
Instance1Database1Enable
Instance1Database2Enable
Instance1Database3Enable
Instance2Database1 Enable
Instance2Database2Enable
My requirement is I should get two table formatted email like below:
Database status of Instance 1
ServerInstance DatabasenameEnabledStatus
Instance1Database1Enable
Instance1Database2Enable
Instance1Database3Enable
Database status of Instance 2
ServerInstance DatabasenameEnabledStatus
Instance2Database1 Enable
Instance2 Database2 Enable
#This PowerShell Scrip is well-suited with PowerShell V3.0 #import SQL Server module #Import-Module SQLPS -DisableNameChecking #get all the instances and temporarily store them in a variable $ServerInstances = Get-Content "C:\SQL_Servers.txt" $scriptFile = "C:\restoredetails_mountdrive.sql" $a = "Hi All, <BR> <BR>" $a = $a + "Below is the TESTING Environment. This is an auto-generated mail.<BR><BR>" $a = $a + "<style>" $a = $a + "BODY{background-color:white;}" $a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}" $a = $a + "TH{border-width: 0px;width:150%;cellspacing=0 ;padding: 10px;border-style: solid;border-color: black;background-color:#43B2B2;font-family: Verdana;font-size:13 }" $a = $a + "TD{border-width: 0px;width:150%;cellspacing=3 ;padding: 10px;border-style: solid;border-color: black;text-align: left;background-color:white;font-family: Verdana;font-size:11}" $a = $a + "</style>" #he database we want to execute it against, regardless of the instance $DBName = "master" #iterating through all instances. $ServerInstances | ForEach-Object { #For each instance, we create a new SMO server object $ServerObject = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $_ #use the Invoke-Sqlcmd cmdlet to execute the query #we are passing in the pipeline is the instance name, which is $_ $refresh_output1 = $refresh_output1 + (Invoke-Sqlcmd ` -ServerInstance $_ ` -Database $DBName ` -InputFile $scriptFile #-Query $SQLQuery ) [string]$tst = $refresh_output1 |convertTo-Html -Head $a -property InstanceName, DatabaseName,OverallStatus | Out-String write-output " " } [System.Net.Mail.MailMessage]$message = New-Object System.Net.Mail.MailMessage("emailid.com", "toemailid.com", "Subject", $tst ) [System.Net.Mail.SmtpClient]$client = New-Object System.Net.Mail.SmtpClient("smtpserver",25) $Message.IsBodyHtml = $true $client.Timeout = 100 $client.Send($message)