Skip to content

Instantly share code, notes, and snippets.

@SteveL-MSFT
Last active February 23, 2021 00:06
Show Gist options
  • Save SteveL-MSFT/3c682138fa329164567387e4daa3cb84 to your computer and use it in GitHub Desktop.
Save SteveL-MSFT/3c682138fa329164567387e4daa3cb84 to your computer and use it in GitHub Desktop.
function Format-Table {
param([parameter(valuefrompipeline=$true)]$inputObject)
begin {
$objects = [System.Collections.Generic.List[PSObject]]::new()
}
process {
$objects += $inputObject
}
end {
$formatData = Get-FormatData -TypeName $inputObject.GetType()
$tableControl = $formatData.FormatViewDefinition | Where-Object { $_.Control -is [System.Management.Automation.TableControl] }
if ($tableControl -ne $null) {
$htmlBuilder = [System.Text.StringBuilder]::new()
$null = $htmlBuilder.Append("<table><thead><tr>")
$headerIndex = 0
foreach ($header in $tableControl.Control.Headers) {
$null = $htmlBuilder.Append("<th")
switch ($header.Alignment) {
"Left" {
$null = $htmlBuilder.Append(" align='left'>")
}
"Right" {
$null = $htmlBuilder.Append(" align='right'>")
}
"Center" {
$null = $htmlBuilder.Append(" align='center'>")
}
default {
$null = $htmlBuilder.Append(">")
}
}
if ($header.Label -ne $null) {
$null = $htmlBuilder.Append($header.Label)
}
else {
$null = $htmlBuilder.Append($tableControl.Control.Rows.Columns[$headerIndex].DisplayEntry.Value)
}
$null = $htmlBuilder.Append("</th>")
$headerIndex++
}
$null = $htmlBuilder.Append("</thead><tbody>")
foreach ($obj in $objects) {
$null = $htmlBuilder.Append("<tr>")
foreach ($displayEntry in $tableControl.Control.Rows.Columns.DisplayEntry) {
$null = $htmlBuilder.Append("<td>")
switch ($displayEntry.ValueType.ToString()) {
'ScriptBlock' {
$value = $obj | ForEach-Object -Process ([scriptblock]::Create($displayEntry.Value))
$null = $htmlBuilder.Append($value)
}
'Property' {
$null = $htmlBuilder.Append($obj.($displayEntry.Value))
}
}
$null = $htmlBuilder.Append("</td>")
}
$null = $htmlBuilder.Append("</tr>")
}
$null = $htmlBuilder.Append("</tbody></table>")
$htmlBuilder.ToString() | Get-HtmlContent | Out-Display
}
else {
Write-Warning "Table control not found!"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment