Powershell Email body formatting not showing as expected - powershell

The code gathers ping and traceroute info and send it in an email. The output of ping result comes out fine in the email's body but tracert info is not formatted correctly. Please see the example below as seen in the email body. The information must be passed on from variable to the body of email as its done below and not attached as a logfile.
The code is as below:
$TimeSpan = New-TimeSpan -Minutes 1
$EndTime = (Get-Date).AddMinutes($TimeSpan.TotalMinutes).ToString("HH:mm")
# $log_file='c:\timee.log'
cls
do
{
write-host 'Gathering logs..wait 2 mins'
$1+=ping google.com |Select-String "Reply"| foreach $_ { $a = Get-Date;
$a.ToString() + " " + $_ } #|
Out-File -Append -Encoding UTF8 -FilePath $log_file
$2+= tracert google.com
}
until ($EndTime -eq (Get-Date -Format HH:mm))
$EmailFrom = "from#gmail.com"
$EmailTo = "to#hotmail.com"
$Subject = "Notification from yy"
$Body = $1+$2
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object
System.Net.NetworkCredential("from#gmail.com",
"passwd");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
#Clear-Variable -name '1'
Write-Host "All done" -ForegroundColor Green

Related

Powershell scripts to send multiple attachements as HTML format

I have prepared the below scripts to send multiple files as HTML format (not as attachments). But it is adding the company disclaimer within the table of 1st report while sending email.
[No issue with 2nd report].
############ START ############
$report = "C:\Reports\ADReport16.htm"
$report1 = "C:\Reports\ADReport26.htm"
$BodyReport1 = Get-Content "$report" -Raw
$BodyReport2 = Get-Content "$report1" -Raw
$BodyReport1 += $BodyReport2
Send-MailMessage -SmtpServer '10.10.10.10' -From 'AD.REPORT#microsoft.com' -To 'xxx.zzz#cisco.net' -Subject "Active Directory Health Report" -Body $BodyReport1 -BodyAsHtml
############ END ############
After reproducing from my end, I could able to make this work by setting IsBodyHtml to $true Below is the complete script that worked for me.
$report = "Report1.html"
$report1 = "Report2.html"
$BodyReport1 = Get-Content "$report" -Raw
$BodyReport2 = Get-Content "$report1" -Raw
$BodyReport1 += $BodyReport2
$emailPassword = "<PASSWORD>"
$emailCredential = New-Object System.Net.NetworkCredential("<EMAIL>", $emailPassword)
$smtpServer = "smtp.office365.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Port = 587
$smtp.EnableSSl = $true
$smtp.Credentials = $emailCredential
$messageObject = new-object Net.Mail.MailMessage
$messageObject.IsBodyHtml = $true
$messageObject.From = "<FROM>"
$messageObject.To.add("<TO>")
$msg.subject = "<SAMPLE_SUBJECT>"
$msg.body = $BodyReport1
$smtp.Send($msg)
RESULTS:

Powershell RDS CAL email Report

I have a PowerShell command that will get an output of how many CAL's I have installed and how many are used. I would like to instead of write-host, change it to a variable so that I can add it to the body of an email and have it run on a schedule, to email me weekly reports on usage, I would like to have the variable something like $report as shown in the $body of the email, this is what I have so far..
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$summaryEntries|ForEach {Write-Host $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "Alert: CAL USAGE "
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)
I have used both parts of this script separately, but I would like to join them together, to make more useful. Thanks in advance PowerShell newbie..
Here is the full code that I used to get this to work, simply changing 'Write-Host' to 'Write-Output'
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$Report = $summaryEntries|ForEach {Write-Output $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "RDS CAL USAGE REPORT"
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)

Power Shell: If condition variable comparison not working

I have a piece of code comparing two values, and if the condition is satisfied it sends out an email. But it is not working, help is appreciated.
code:
$filesize = Get-ChildItem $filename | Select-Object Length | Format-Wide
$filesize
$num=1265
$num
if("$filesize" -gt "$num")
{
$SMTPServer = "10.20.19.94"
$SMTPPort = 25
$username = "vcenter#somosadc.com"
#Define the receiver of the report
$to = "jeevan.m2#hcl.com"
$subject = "VM Snapshot Report"
$body = "VM Snapshot Report"
$attachment = new-object Net.Mail.Attachment($filename)
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $body
$message.to.add($to)
$message.from = $username
$message.attachments.add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $false
#$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent"
}
output:
1262
1265
Mail Sent
Why is it sending email if $filesize=1262 is less than $num=1265. It is killing me.
Because you're not comparing two numbers, you're comparing two strings.
Remove the Format-Wide command from the first pipeline, and remove the quotes around the arguments in your if condition:
$filesize = Get-ChildItem $filename | Select-Object Length
$num = 1265
if($filesize.Length -gt $num) {
<# ... #>
}

New to error handling

The path that I have set is not valid, when the copy fails I want to send an email to someone. If there is no error then send an email stating the copy was successful.
Current it doesnt give me an error and it doesnt send an email. I know that the email part is correct and confirmed it does work.
My script block.
try
{
Copy-Item -path "\\main-
4\info\SmartPlant\app\CitrixRelease\domain\app\*" -Destination "\\domain.com\citrix\Installation Media\app\" -force -ErrorAction Stop
}
catch
{
$from = "alerts#domain.com"
$to = "me#domain.com"
$subject = "Copy Failed"
$body = "The Copy failed to complete, please make sure the servers rebooted"
$msg = "$file"
$Attachment = "$file"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient("mail.domain.com")
$msg.From = $From
$msg.To.Add($To)
if($Attachment.Length -gt 1)
{
$msg.Attachments.Add($Attachment)
}
$msg.Subject = $Subject
$msg.IsBodyHtml = $true
$msg.Body = $Body
$smtp.Send($msg)
}
How about this as a solution for sending an email for both failure and success without duplicating the email send code:
$Status = 'Succeeded'
try{
Copy-Item -path "\\main-4\info\SmartPlant\app\CitrixRelease\domain\app\*" -Destination "\\domain.com\citrix\Installation Media\app\" -force -ErrorAction Stop
}catch{
$Status = 'Failed'
}finally{
$from = "alerts#domain.com"
$to = "me#domain.com"
$subject = "Copy $Status"
$body = "The Copy $Status"
If ($Status = 'Failed') {$body += ", please make sure the server is rebooted" }
$Attachment = "$file"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient("mail.domain.com")
$msg.From = $From
$msg.To.Add($To)
if($Attachment.Length -gt 1){
$msg.Attachments.Add($Attachment)
}
$msg.Subject = $Subject
$msg.IsBodyHtml = $true
$msg.Body = $Body
$smtp.Send($msg)
}
You don't really need to use a Finally block, but it does create a nice code block to make explicit what the email functionality belongs to.

Adding Get-WMI Data To E-mail Body

I've got this script that I found that simply sends the time the script was run in an e-mail to the recipient.
function send-email
{
$time = get-date
$EmailFrom = “from”
$EmailTo = “To”
$Subject = “ADX Has Been Deployed”
$Body = “Script has been used on: ” + $time
$SMTPServer = “smtp.gmail.com”
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“e-mail address”, “password”);
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}
send-email
This works a treat, however when I try and add some data into the body of the e-mail using the below code (hostname, IP Address, etc), the data is returned as a complete string.
$a = #()
$systeminfo = get-wmiobject win32_computersystem | select *
foreach ($item in $systeminfo)
{
$a = $item
}
Basically, what I'm after is for the data to be presented in the e-mail one line at a time.
Any ideas?
Thanks
$a = #()
$systeminfo = get-wmiobject win32_computersystem | select *
foreach ($item in $systeminfo)
{
$a += $item
}
$body = [string]::Join("`n", $a)