Fix ANSI control characters before PowerShell output to a file

孤人 提交于 2019-12-11 16:45:18

问题


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)


回答1:


You could try something like this:

... | ForEach-Object {
    $_ -replace '\[\d+(;\d+)?m' | Add-Content 'C:\path\to\output.txt'
    $_
}

or wrap it in a function:

function Tee-ObjectNoColor {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
        [string]$InputObject,

        [Parameter(Position=1, Mandatory=$true)]
        [string]$FilePath
    )

    Process {
        $InputObject -replace '\[\d+(;\d+)?m' | Add-Content $FilePath
        $InputObject
    }
}

... | Tee-ObjectNoColor -FilePath 'C:\path\to\output.txt'



回答2:


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.



来源:https://stackoverflow.com/questions/45703539/fix-ansi-control-characters-before-powershell-output-to-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!