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
}
}
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 one was previously marked a duplicate of.
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.
Utilities (command-line programs) that support colorized output usually omit color codes when their stdout is not connected to a terminal (console), such as when output is redirected to a file or sent through the pipeline.
In that event you must use a utility-specific option, IF supported in order to force unconditional use of coloring.
PowerShell does pass color codes through the pipeline, so something like the following, executed from a directory with a git
repository, should produce colored output.
PS> git -c color.status=always status -b --short | % { $i=0 } { "$((++$i)): $_" }
1: ## master
The word master
(or whatever branch is active) should appear in green.
The answer from which the -c color.status=always
technique is taken was updated since you linked to it, so I suspect that an earlier form was simply not effective in forcing unconditional colored output.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With