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
PSCustomObjectinsideForEach-Objectto control howServerEventsis processed. - If
ServerEventsis 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-Htmlprocesses the object, it gets a plain string instead of an array, so it will renderEVENT1, EVENT2, EVENT3correctly.
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
相关产品推荐
相关产品推荐

