Render an Aligned Plain-Text Table in PowerShell
PowerShell
function Format-TextTable {
param(
[Parameter(Mandatory)][object[]]$Rows,
[string[]]$Columns
)
if (-not $Columns) { $Columns = $Rows[0].PSObject.Properties.Name }
$widths = @{}
foreach ($column in $Columns) {
$max = ($Rows | ForEach-Object { [string]$_.$column } | Measure-Object -Maximum Length).Maximum
$widths[$column] = [Math]::Max($max, $column.Length)
}
($Columns | ForEach-Object { $_.PadRight($widths[$_]) }) -join ' | '
($Columns | ForEach-Object { '-' * $widths[$_] }) -join '-+-'
foreach ($row in $Rows) {
($Columns | ForEach-Object { ([string]$row.$_).PadRight($widths[$_]) }) -join ' | '
}
}