dir
color output to file
If I run the following command on Ubuntu:
dharmatech@dharmatech-01:/tmp$ pwsh -Command 'dir' > out.txt
and then cat the output:
dharmatech@dharmatech-01:/tmp$ cat out.txt
the colors are rendered:
The colors are represented in out.txt
as escape codes:
Write-Host colors
Here I’m using Write-Host
to display text in red:
However, if I redirect output to a file, we can see that this time the colors are not represented in the resulting file:
Question
Is there a way to get the colors in the file in the Write-Host
case as they are with the dir
command?
2
Answers
Here's one approach using the
script
command from bsdutils:This is based on this answer:
Use case
As an aside, by combining this approach with
terminal-to-html
:I'm able to render arbitrary colored PowerShell output as HTML.
Here's a screenshot which renders output from this PowerShell script as HTML:
This should be possible since Powershell 7.2, as it has support for ANSI colors. Credit for this goes to an earlier answer.
As for an example (Powershell 7.3.3. / MacOS, YMMV):
Examining the file with, say,
vi
displays the Ansi color codes: