Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To arrange and transform a pscustomobject into an HTML table, you can use the following steps:

  1. Create an empty string variable or StringBuilder to store the HTML code for the table.
  2. Use the Get-Member cmdlet to get the properties of the pscustomobject and store them in an array.
  3. Start building the HTML table code by adding the tag.
  4. Add the
  5. tag to define the header row of the table.
  6. Create a loop to iterate through the properties of the pscustomobject and add each property as a
  7. tag.
  8. Add the
  9. tag to define the body of the table.
  10. Loop through the pscustomobject, creating a new row for each object in the table.
  11. Within each row, loop through the properties of the pscustomobject and add each property value as a
  12. tag under the
    tag.
  13. Add the closing
  14. tag to finish the HTML code for the table.

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()