For some reason the ANSI Escape colors in use with Format-Table loses the column alignment. Any suggestions to correct this behavior? The line that is causing this issue is
"$e[${color}m$($dbValue)${e}[0m"
Yet, if we don't use ANSI Escape the function works fine.
Expected results (colors removed)
id author title genre price publish_date
-- ------ ----- ----- ----- ------------
Bk001 LName, FName XML Powershell Guide Computer 104.95 2020-10-01
Bk002 LName2, FName2 Python Guide Computer 104.95 2020-12-16
Current results (colors removed)
id author title genre price publish_date
-- ------ ----- ----- ----- ------------
Bk001 LName, FName XML Powershell Guide Computer 104.95 2020-10-01
Bk002 LName2, FName2 Python Guide Computer 104.95 2020-12-16
$myBooks = [xml] @"
<catalog>
<book id="Bk001">
<author>LName, FName</author>
<title>XML Powershell Guide</title>
<genre>Computer</genre>
<price>104.95</price>
<publish_date>2020-10-01</publish_date>
</book>
<book id="Bk002">
<author>LName2, FName2</author>
<title>Python Guide</title>
<genre>Computer</genre>
<price>104.95</price>
<publish_date>2020-12-16</publish_date>
</book>
</catalog>
"@
# Colors
# Red 31
# Green 32
$ColorRed = '31'
$ColorGreen = '32'
function ColorValue {
param (
[Parameter(Mandatory = $False)][string]$dbValue,
[Parameter(Mandatory = $False)][string]$color
)
$e = [char]27
if ($color -eq [string]::Empty) {
$color = $ColorGreen
}
if ([string]::IsNullOrWhiteSpace($dbValue)) {
$dbValue = 'NULL'
$color = $ColorRed
}
"$e[${color}m$($dbValue)${e}[0m"
}
# title, genre, price, publish_date
$myBooks.catalog.book | Format-Table -AutoSize -Wrap -Property id, author,
@{name = 'title'; expression = { (ColorValue $_.title)}},
@{name='genre';expression={ColorValue $_.genre $ColorRed}} , price, publish_date
> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.18362.752
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.18362.752
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
Even upgrading to PowerShell 5.1.19041.1 the issue remains. It is actually happening in VS Code PowerShell Terminal rather than PowerShell... Go figure. Any workaround for VS Code or file it as a bug?
It turns out the issue isn't in the code but rather the VS Code: PowerShell extension. Filed this as a bug: https://github.com/PowerShell/vscode-powershell/issues/2815