I am trying to use Powershell to output a table with some pre/post content and then email it, but the pre/post content is showing up in the email as "System.String[]." The rest of the content seems fine, and if I output the HTML string to the console, everything looks fine.
function Send-SMTPmail($to, $from, $subject, $smtpserver, $body) {
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)
$msg.IsBodyHTML = $true
$mailer.send($msg)
}
$Content = get-process | Select ProcessName,Id
$headerString = "<table><caption> Foo. </caption>"
$footerString = "</table>"
$MyReport = $Content | ConvertTo-Html -fragment -precontent $headerString -postcontent $footerString
send-SMTPmail "my Email" "from email" "My Report Title" "My SMTP SERVER" $MyReport
Shows up in my email as:
System.String[]
ProcessName Id
... ...
System.String[]
Doing an out-file and then an invoke-item has the same results as sending the email...
ConvertTo-Html returns a list of objects - some are strings and some are string arrays e.g.:
So $MyReport contains an array of both strings and string arrays. When you pass this array to the MailMessage constructor, which expects type string, PowerShell attempts to coerce that to a string. The result is:
The easy solution is to run the output of
ConverTo-Html
throughOut-String
which will cause $MyReport to be a single string: