转换为 HTML 输出前/后内容显示为 System.String[] 而不是实际内容
我正在尝试使用 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[]
执行输出文件,然后调用项目与发送电子邮件具有相同的结果...
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ConvertTo-Html 返回一个对象列表 - 有些是字符串,有些是字符串数组,例如:
因此 $MyReport 包含字符串和字符串数组的数组。当您将此数组传递给需要字符串类型的 MailMessage 构造函数时,PowerShell 会尝试将其强制转换为字符串。结果是:
简单的解决方案是通过
Out-String
运行ConverTo-Html
的输出,这将使 $MyReport 成为单个字符串: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:Convertto-html 返回字符串列表,而不是字符串。所以我认为 $myreport 最终成为一个对象数组;例如,试试这个:
在将 $myreport 传递给 send-SMTPMail 之前强制将其设置为字符串:
convertto-html returns a list of strings, not a string. So I think $myreport ends up being an object array; e.g., try this:
Instead force $myreport to be a string before passing it to send-SMTPMail: