2011-02-09 68 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