Adrian Dymorz
Adrian Dymorz

Reputation: 967

Remove colour codes from output of an executable in powershell

The following script removes all the colour codes from an output of an executable:

gulp test | ForEach-Object -Process {$_ -replace "$([char]27)\[[0-9]*m", ""}

But it has got (at least) two problems:

How do I get rid of the colour codes in an output of an executable without waiting for the process to finish?


Output of gulp test:

enter image description here

Output of the above script:

enter image description here

Upvotes: 2

Views: 379

Answers (1)

mklement0
mklement0

Reputation: 440556

Instead of trying to strip color codes after the fact, instruct gulp not to produce colored output to begin with:

gulp test --no-color

This should make your two other problems go away as well, but just to address them briefly:

  • Use gulp test 2>&1 to merge stderr and stdout output, which would send the lines in proper sequence to ForEach-Object - note that stderr lines will be of type [System.Management.Automation.ErrorRecord] (which is helpful for determining what stream a particular line came from).

  • To fix the problem with the misinterpreted characters, first set [console]::OutputEncoding to match the output character encoding used by gulp, which I presume is UTF-8 ([console]::OutputEncoding = [Text.Encoding]::Utf8)

Upvotes: 3

Related Questions