1 | initial version |
To arrange and transform a pscustomobject into an HTML table, you can use the following steps:
tag under the |
---|
tag.
|
Here is an example of how to do this in PowerShell:
$table = Get-Process | Select -First 5 | ConvertTo-Html -Fragment
$obj = $table -replace '<td>','<td style="text-align:center;background-color:#eee;">' |
ConvertFrom-Html |
Select-Object -ExpandProperty body |
Select-Object -Skip 3 |
Select-Object -SkipLast 1 |
Where-Object {
$_ -notmatch '<thead>|<th>|</th>|</thead>|<t[rd]>|</t[rd]>' -and
$_ -match '<td>'
} |
ForEach-Object {
$temp = $_ -split '<td>' |
Where-Object { $_ -ne '' }
$props = [ordered]@{}
foreach ($item in $temp) {
switch ($item) {
{ $_ -match '^(.+)</td>$' } {
$name, $value = $matches[1] -split ':', 2
try {
$props.Add($name.Trim(), $value.Trim())
} catch { }
}
}
}
[PSCustomObject]$props
}
$HTMLTable = New-Object -TypeName System.Text.StringBuilder
$HTMLTable.Append("<table>")
# Get the pscustomobject properties as an array
$properties = $obj | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
# Create the table header row
$headerRow = "<thead><tr>"
foreach ($property in $properties) {
$headerRow += "<th>$property</th>"
}
$headerRow += "</tr></thead>"
$HTMLTable.AppendLine($headerRow)
# Create the table body
$bodyRows = "<tbody>"
foreach ($row in $obj) {
$bodyRow = "<tr>"
foreach ($property in $properties) {
$bodyRow += "<td>" + $row.$property + "</td>"
}
$bodyRow += "</tr>"
$bodyRows += $bodyRow
}
$bodyRows += "</tbody>"
$HTMLTable.AppendLine($bodyRows)
$HTMLTable.Append("</table>")
# Print the HTML table code
$HTMLTable.ToString()