Fix ANSI control characters before PowerShell output to a file

Viewed 3402

Is there anyway for PowerShell to output a file without ANSI control characters like color control, e.x. [1;xxm or [xm], before outputting to a file,

[1;35mStarting selenium server... [0m[1;35mstarted - PID: [0m 22860

[0;36m[Signin Test] Test Suite[0m
[0;35m================================[0m

Running:  [0;32mstep 1 - launch the browser[0m
[1;35m[40mINFO[0m [1;36mRequest: POST /wd/hub/session[0m

The output displays correctly with color in PowerShell terminal, (I've used chcp, not working)

click to view image

2 Answers

For the windows system one could use the Replace command available as a part of Powershell 3.0.The powershell makes use of regex expression that helps to replace the ANSI Color codes. (In case of UNIX one could use the sed command )

Using Regex

Below is the standard Regex for removing ANSI color codes (can be used in Linux and windows both)

'\x1b\[[0-9;]*m'
  • \x1b (or \x1B) is the escape special character
    (sed does not support alternatives \e and \033)
  • \[ is the second character of the escape sequence
  • [0-9;]* is the color value(s) regex
  • m is the last character of the escape sequence

Final Command

I am here outputting the logs of docker to a log file.One could do the same for other commands

docker logs container | ForEach-Object { $_ -replace '\x1b\[[0-9;]*m','' }| Out-File -FilePath .\docker-logs.log

  • ForEach-Object refers to each object from the pipped stream and $_ refers to current object.

The above command will remove the special characters like [1;35m , [0m[1;3 and ^[[37mABC from the output stream.

Related