Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get carriage return in my email body in powershell script?

I have created a powershell script to gather some system stats and email them, I would like to get carriage returns in the body so that everything is not jumbled up.

Anyone know how I would archieve this with the script below?

Process{
 $strComputerName = (Get-WmiObject -Class Win32_ComputerSystem | Select-Object Name).Name
 $strComputerModel = (Get-WmiObject -Class Win32_ComputerSystem | Select-Object Model).Model
 $strSerialNumber = (Get-WmiObject -Class Win32_BIOS | Select-Object SerialNumber).SerialNumber
 $strDate = Get-Date
 $erroractionpreference = "SilentlyContinue"
 $strSMTP = $server
 $strSubject = $subject
 $strBody = "Hostname: $strComputerName Model: $strComputerModel Serial: $strSerialNumber Date: $strDate"
 $MailMessage = New-Object System.Net.Mail.MailMessage
 $MailMessage.IsBodyHtml = $true
 $SMTPClient = New-Object System.Net.Mail.smtpClient
 $SMTPClient.host = $strSMTP
 $Sender = New-Object System.Net.Mail.MailAddress($from, "ConfigMgr")
 $Recipient = New-Object System.Net.Mail.MailAddress($to)
 $MailMessage.Sender = $Sender
 $MailMessage.From = $Sender
 $MailMessage.Subject = $strSubject
 $MailMessage.To.add($Recipient)
 $MailMessage.Body = $strBody
 $SMTPClient.Send($MailMessage)
}

Trying to get CR for the $strBody output.. anyone?

Thanks :)


2 Answers

There are several ways to achieve this.

If you just want to separate items in the assignment to $strBody as showed in your code i would change the line to.

$strBody = "Hostname: $strComputerName`r`n Model: $strComputerModel`r`n Serial: $strSerialNumber`r`n Date: $strDate"

backtick+r and backtick+n is the powershell escape sequence for Carriage Return and Newline.

You could also use the constant from the Environment class like this.

$strBody = "Hostname: $strComputerName{0} Model: $strComputerModel{0} Serial: $strSerialNumber{0} Date: $strDate" -f [Environment]::NewLine

Let me know if i misunderstood your question or if it does not work for you.

like image 162
Jower Avatar answered Nov 23 '25 09:11

Jower


Neither (backtick)n nor (backtick)r(backtick)n work when using Send-MailMessage. I had to switch to HTML.

 Send-MailMessage -From [email protected] -To "[email protected]" 
   -SmtpServer foo.bar.com -Subject "my subject" 
   -Body ($fileText -join "<br/>") -BodyAsHtml

Where $fileText was an array of strings.

like image 40
mhenry1384 Avatar answered Nov 23 '25 10:11

mhenry1384



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!