You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell发送HTML邮件报表异常:显示格式对象而非统计数据

PowerShell发送HTML邮件报表异常问题解决

问题描述

尝试通过PowerShell发送HTML格式的邮件报表,但邮件正文未显示预期的用户名及计数,反而输出一堆格式对象的内部属性:

ClassId2e4f51ef21dd47e99d3c952918aff9cd pageHeaderEntry pageFooterEntry autosizeInfo    shapeInfo   groupingEntry
033ecb2bc07a4d43b5ef94ed5a35d280                Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo   
9e210fe47d09416682b841769c78b8a3                    
27c87ef9bbda4f709f6b4002fa4af63c                    
27c87ef9bbda4f709f6b4002fa4af63c                    
27c87ef9bbda4f709f6b4002fa4af63c                    
27c87ef9bbda4f709f6b4002fa4af63c                    
27c87ef9bbda4f709f6b4002fa4af63c                    
27c87ef9bbda4f709f6b4002fa4af63c                    
4ec4f0187cb04f4cb6973460dfe252df                    
cf522b78d86c486691226b40aa69e95c

使用的代码如下:

$list = Import-Csv -Path $csvfile -Delimiter ","
$pivot = ($list | Group-Object -Property User -NoElement | Where-Object {$_.Name -ne ""} | Select-Object Name,Count | Format-Table)
$out = $pivot | ConvertTo-Html | Out-String
Send-MailMessage -SmtpServer $smtpServer -To $to -From $from -Subject $subject -Body $out -BodyAsHtml -Attachments $csvfile -WarningAction:SilentlyContinue

问题根源

你在管道末尾添加了Format-Table命令,这个命令的作用是生成仅用于控制台可视化输出的格式对象,而非保留原始的数据对象。当你把这些格式对象传给ConvertTo-Html时,它会解析格式对象的内部元数据(比如ClassId、表头信息等)并转换成HTML,自然不会显示你需要的用户名和计数数据。

解决方案

移除Format-Table,直接将筛选后的原始数据对象传递给ConvertTo-Html即可。ConvertTo-Html会自动识别对象的属性(Name和Count)并生成对应的HTML表格。

修正后的代码

$list = Import-Csv -Path $csvfile -Delimiter ","
# 移除Format-Table,保留原始数据对象
$pivot = $list | Group-Object -Property User -NoElement | Where-Object {$_.Name -ne ""} | Select-Object Name,Count
$out = $pivot | ConvertTo-Html | Out-String
Send-MailMessage -SmtpServer $smtpServer -To $to -From $from -Subject $subject -Body $out -BodyAsHtml -Attachments $csvfile -WarningAction:SilentlyContinue

可选:自定义HTML表格样式

如果需要美化报表样式,可以给ConvertTo-Html添加-Head参数注入CSS:

$list = Import-Csv -Path $csvfile -Delimiter ","
$pivot = $list | Group-Object -Property User -NoElement | Where-Object {$_.Name -ne ""} | Select-Object Name,Count

# 自定义表格样式
$cssStyle = @"
<style>
table { border-collapse: collapse; width: 90%; margin: 15px auto; font-family: Arial, sans-serif; }
th { background-color: #4CAF50; color: white; padding: 10px; text-align: left; }
td { border: 1px solid #ddd; padding: 8px; }
tr:nth-child(even) { background-color: #f2f2f2; }
</style>
"@

$out = $pivot | ConvertTo-Html -Head $cssStyle -Title "用户操作计数报表" | Out-String
Send-MailMessage -SmtpServer $smtpServer -To $to -From $from -Subject $subject -Body $out -BodyAsHtml -Attachments $csvfile -WarningAction:SilentlyContinue

内容的提问来源于stack exchange,提问作者George

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:42:45