1

我正在尝试使用 Powershell 输出包含一些前/后内容的表格,然后通过电子邮件发送,但前/后内容在电子邮件中显示为“System.String []”。其余的内容看起来都很好,如果我将 HTML 字符串输出到控制台,一切看起来都很好。

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

在我的电子邮件中显示为:

System.String[]
ProcessName Id
...             ...
System.String[]

做一个输出文件,然后一个调用项与发送电子邮件的结果相同......

4

2 回答 2

5

ConvertTo-Html 返回一个对象列表 - 有些是字符串,有些是字符串数组,例如:

407# $headerString = "<table><caption> Foo. </caption>"
408# $footerString = "</table>"
409# $content = Get-Date | select Day, Month, Year
410# $MyReport = $Content | ConvertTo-Html -Fragment -PreContent $headerString `
                                           -PostContent $footerString
411# $MyReport | Foreach {$_.GetType().Name}
String[]
String
String
String
String
String
String
String
String
String
String[]

所以 $MyReport 包含一个字符串数组和字符串数组。当您将此数组传递给需要字符串类型的 MailMessage 构造函数时,PowerShell 会尝试将其强制转换为字符串。结果是:

412# "$MyReport"
System.String[] <table> <colgroup> <col/> <col/> <col/> </colgroup> <tr><th>Day
</th><th>Month</th><th>Year</th></tr> <tr><td>9</td><td>2</td><td>2011
</td></tr> </table> System.String[]

简单的解决方案是运行ConverTo-Html通过Out-Stringwhich 将导致 $MyReport 成为单个字符串的输出:

413# $MyReport = $Content | ConvertTo-Html -Fragment -PreContent $headerString `
                                           -PostContent $footerString |
                            Out-String
414# $MyReport | Foreach {$_.GetType().Name}
String
于 2011-02-09T22:44:44.453 回答
0

convertto-html 返回字符串列表,而不是字符串。所以我认为 $myreport 最终成为一个对象数组;例如,试试这个:

$Content = get-process | Select ProcessName,Id
$headerString = "<table><caption> Foo. </caption>"
$footerString = "</table>"
$MyReport = $Content | ConvertTo-Html -fragment -precontent $headerString -postcontent $footerString
get-member -input $MyReport

而是强制 $myreport 在将其传递给 send-SMTPMail 之前成为一个字符串:

$MyReport = ( $Content | ConvertTo-Html -fragment -precontent $headerString -postcontent $footerString ) -join "`n";
于 2011-02-09T21:34:05.327 回答