skip to Main Content

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:

enter image description here

The colors are represented in out.txt as escape codes:

enter image description here

Write-Host colors

Here I’m using Write-Host to display text in red:

enter image description here

However, if I redirect output to a file, we can see that this time the colors are not represented in the resulting file:

enter image description here

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


  1. Chosen as BEST ANSWER

    Here's one approach using the script command from bsdutils:

    enter image description here

    This is based on this answer:

    https://stackoverflow.com/a/27399198/268581

    Use case

    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

    enter image description here


  2. 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
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search