In PowerShell, is there a way to preserve the ANSI control codes used to convey color information to the console when assigning a program's output to a variable?
For instance, I use Test Kitchen which provides colored output unique to each suite of tests to run. When I run kitchen create INSTANCE
, I get output in several colors. However, if I assign the output to a variable, or pipe it to another cmdlet such as Tee-Object
, that color information is lost. It seems that PowerShell strips this information out when the result is sent down the pipeline or assigned to a variable:
kitchen create INSTANCE # Colored output
$output = kitchen create INSTANCE
Write-Host $output # Color information is lost
Curiously though, I can implement control codes in my own strings and PowerShell is able to honor them when Virtual Terminal is enabled. These survive variable assignment, unlike command output:
$output = "`u{001b}[31mHello"
Write-Host $output # Results in colored output
So it seems that the color information is being stripped out only from a program's output, and only if the value is assigned or sent down the pipeline. Is there a way to preserve these control codes from external commands?
[pscustomobject]@{type="error";output=$results}
this way you can work with the object with a foreach loop and switch/if cases... and if you just want the output, you could dowrite-host $results.output
you could even have a parameter switch that sayskitchen create instance -colorTag
which could enable the tagging feature but i'm not sure what language your kitchen function/command is written in. instead of type="error" you could do color="red" – Euforce-color
option. – Empyrean