dir
color output to fileIf 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:
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:
Is there a way to get the colors in the file in the Write-Host
case as they are with the dir
command?
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):
$PsStyle.OutputRending = "Ansi"
$s = Get-ChildItem | Select -First 3 | Out-String
Set-Content -path foo.txt $s
Get-Content ./foo.txt # prints out colored output
Examining the file with, say, vi
displays the Ansi color codes:
...
^[[32;1mUnixMode User Group LastWriteTime Size Name^[[0m
^[[32;1m-------- - ----- ------------- ---- ----^[[0m
...
Here's one approach using the script
command from bsdutils:
This is based on this answer:
https://stackoverflow.com/a/27399198/268581
As an aside, by combining this approach with terminal-to-html
:
https://github.com/buildkite/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:
https://github.com/dharmatech/net-liquidity.ps1
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