Roy T. Roy T. - 1 month ago 7x
PowerShell Question

Preserve color from piped output

I have this extremely simple powershell script that prepends each line with a number.

function number
$i = 0;
foreach($line in $input)
[string]$i + ":" + $line

I would like this function to preserve the colors of the input. For example if I execute the following command the colors are lost:

git status -s | number

While executing

git status -s

Gives me a nicely colored output. What can I change in my powershell function to accomplish this.

Note I've already tried telling git to always output colors with the information in the answers to this question so I think its my side that is ignoring the colors.

This is not a duplicate of the question this is now linked to.

I've seen that question, which is actually about how to prevent MSBuild from writing to standard error instead of standard out, which prevented the colors from showing up in that case. The only thing similar about that question and this one is the title. The other answer there (with HTML conversion) does not apply here as that requires the data is written to the console and not piped.


As far as I'm aware, you can't preserve the colors output by git status -s, or any other command output that is piped into PowerShell via StdIn. The color information of the text being piped into the PowerShell function via StdIn is 'lost'.

The only way I can think of adding color back in would be to perform RegEx matches or positional based coloring, using multiple Write-Host "line section" -ForegroundColor COLOR -NoNewline for each colored section.

The console uses System.IO.StreamReader to accept input via StdIn. Try this command [Console]::In | Get-Member in PowerShell/ISE.