Heyvoon
Heyvoon

Reputation: 71

How to preserve text formatting in Powershell variable output?

I am using the code below on my PS script to catch part of Robocopy output and send it via email but it does not maintain the output format.

$roboresult = (Get-Content $tmpdest\$RoboLog | Select-Object -first 15)
$roboresult += (Get-Content $tmpdest\$RoboLog | Select-Object -last 10)
$roboresult

It comes out on the email like the following (Not formatted);

------------------------------------------------------------------------------- ROBOCOPY :: Robust File Copy for Windows
------------------------------------------------------------------------------- Started : Tue Apr 09 09:27:17 2019 Source : I:~temp\SIGNO\
Dest : \BRC\H$~temp\SIGNO\ Files : . Options : . /X /NDL /NFL /S /E /COPY:DAT /MOVE /Z /NP /MT:8 /R:10 /W:5
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs :
1235 1235 0 0 0 0 Files :
147408 147408 0 0 0 0 Bytes : 79.215 g 79.215 g 0 0 0 0 Times : 27:56:05 2:47:50 0:00:00 0:21:21 Ended : Tue Apr 09 12:36:29 2019

How can I make so I receive in the email formatted?

Upvotes: 1

Views: 2065

Answers (2)

OZOM
OZOM

Reputation: 1

This may be old, but just to share. Try the below snippet.

roboresult += (Get-Content $tmpdest\$RoboLog -Tail 15)

$roboresult = $roboresult -join "`r`n"
Send-MailMessage -BodyAsHtml "<pre><code>$roboresult</code></pre>" ...

Upvotes: 0

AdminOfThings
AdminOfThings

Reputation: 25031

I think this is possible with how you construct your mail message command. If I set up the same situation you have here, I will end up with an $roboresult variable with 25 lines of formatted code. You will need to convert that to a string to use send-mailmessage if you are sending it as the body of the email. If you join each line with CRLF characters, you should preserve the formatting in email.

send-mailmessage -from [email protected] -to [email protected] -subject "Robocopy Results" -body ($roboresult -join "`r`n") -smtpserver servername

Based on your comments, you should be able to replace $roboresult with the following:

$($roboresult -join "`r`n")

Upvotes: 1

Related Questions