2011-02-09 27 views
1

我想使用PowerShell输出一些表格,然后通过电子邮件将其发送给前/后内容在电子邮件中显示为“System.String []”。其余的内容似乎很好,如果我输出HTML字符串到控制台,一切都看起来很好。转换为HTML输出的前/后内容显示为System.String []而不是实际内容

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[] 

做一个彻头彻尾文件,然后一个Invoke项具有相同的结果发送电子邮件...

回答

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[] 

简单的解决方法是通过Out-String运行的ConverTo-Html输出,这将导致$ MyReport是一个字符串:

413# $MyReport = $Content | ConvertTo-Html -Fragment -PreContent $headerString ` 
              -PostContent $footerString | 
          Out-String 
414# $MyReport | Foreach {$_.GetType().Name} 
String 
+0

你已经救了我的理智。 Out-String,FTW。 – JakeRobinson 2011-02-09 22:47:43

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是一个字符串SMTPMail发送之前将其传递给:

$MyReport = ($Content | ConvertTo-Html -fragment -precontent $headerString -postcontent $footerString) -join "`n"; 
+0

我明白你的意思,但没” t修复它。 – JakeRobinson 2011-02-09 21:51:37