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

PowerShell生成邮件HTML表格时数组属性显示异常求助

Fix: Array Property Showing as System.Object[] in PowerShell ConvertTo-Html Table

Got it, let's tackle this issue. The problem here is that when your ServerEvents property is an array, ConvertTo-Html doesn't automatically render the array's contents—it just calls the array's ToString() method, which returns System.Object[] by default.

The Fix: Convert Array to a Readable String

You need to explicitly convert the array property into a string before passing it to ConvertTo-Html. Here's how to modify your code:

$Header = @"
<style>
TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH {border-width: 1px;padding: 4px;border-style: solid;border-color: black;background-color: #0085cc;color: white}
TD {border-width: 1px;padding: 4px;border-style: solid;border-color: black;}
</style>
"@

$TableOutput = $Global:FinalResults | ForEach-Object {
    [PSCustomObject]@{
        ServerName = $_.ServerName
        # Handle arrays by joining elements into a comma-separated string
        ServerEvents = if ($_.ServerEvents -is [array]) { 
            $_.ServerEvents -join ', ' 
        } else { 
            $_.ServerEvents 
        }
    }
} | Select-Object ServerName, ServerEvents | ConvertTo-Html -Head $Header | Out-String

How This Works:

  • We're manually constructing the PSCustomObject inside ForEach-Object to control how ServerEvents is processed.
  • If ServerEvents is an array, we use -join ', ' to concatenate all elements into a single string. For non-array values (like "No events found"), we just keep the original value.
  • Now when ConvertTo-Html processes the object, it gets a plain string instead of an array, so it will render EVENT1, EVENT2, EVENT3 correctly.

Optional: Make It Prettier for Email

If you want each event on its own line in the HTML email, use <br> as the separator instead of a comma:

ServerEvents = if ($_.ServerEvents -is [array]) { 
    $_.ServerEvents -join '<br>' 
} else { 
    $_.ServerEvents 
}

This will display each event in a new line within the table cell, making it easier to read.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:17:09