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()
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-07-28 11:00:00 +0000
Seen: 10 times
Last updated: Jun 28 '21
What is the process for installing SASS/Compass in the DDEV web container?
Is it possible to create and execute a file without having to type the file name twice?
How can you obtain the sha1 of the most recent commit in a git repository using C#?
What is the process for initializing Java UDFs in Spark?
How can I use crontab to initiate and modify the libcamera-vid RTSP stream on my Raspberry Pi?
Is it possible to repair a file within a docker container that has failed to start?
What is an effective way to edit HTML strings using PowerShell?