Powershell: Preserve colors when piping the output

Created on 19 Mar 2018  路  6Comments  路  Source: PowerShell/PowerShell

There is a demand of this feature:

https://stackoverflow.com/q/39245288
https://stackoverflow.com/q/18861709

In Unix, it is possible using --color=always and the pipe will pass the piper's colors to pipee: https://superuser.com/a/352719

Please consider adding this option.

Thanks!

Issue-Question Resolution-Answered

All 6 comments

@kasper3 I the specific case you cite, --color=always is an option on the 'ls' _command_ causing it to always emit color codes regardless of whether the output is a tty or not. So it's up to the command to emit the color codes not the shell. Quoting from the superuser.com example:

you can't easily fix it in tee/pipe as tee/pipe are not stripping these color codes. The problem is that the initial command sees it is not writing to the terminal.

@BrucePay, thanks! I am trying to pipe the output of MSBuild to Out-Default, Write-Host etc. Was wondering if somehow i can preserve the colors. Could that be an option of pipe, perhaps a new pipe syntax ^|, that will push the raw output to RHS?

@kasper3 Unfortunately the change must be made to the command being run (i.e. msbuild) not the shell since it's the command that generates the colors.

Note: the superuser.com mentions a utility unbuffer that (I infer) launches a command with it's output redirected into a pseudo-tty then takes the output of the pseudo-tty and redirects that to the pipeline. This command should work with PowerShell but it's only on Unix/Linux since it depends on pseudo-ttys..

Oh nice, i just found a way to do it while reading @Veigres comments at https://github.com/Microsoft/msbuild/issues/2364:

msbuild /clp:ForceConsoleColor | Write-Host

Retreating this proposal. Thanks for your help!

btw, i have drilled down to the code, https://github.com/Microsoft/msbuild/blob/6851538897f5d7b08024a6d8435bc44be5869e53/src/Deprecated/Engine/Logging/BaseConsoleLogger.cs#L411-L426, maybe it can be opened as API addition in CoreFX to provide property like public bool Console.IsTty if there are other use-cases?

@BrucePay, I found one exception that in PowerShell workflow block (foreach -parallel or inline script etc.), if we invoke msbuild /clp:ForceConsoleColor | Write-Host, and the workflow callsite is using | Out-Default, then the colors are lost. Is this something PowerShell can accommodate (or already does)?

I'd like to know this as well. For programs that _already_ emit colors, that color is lost when piped to Out-Default. How can it be preserved?

Was this page helpful?
0 / 5 - 0 ratings