PowerShell是否可以输出一个没有ANSI控制字符的文件,比如颜色控制,e.x。[1;xxm
或[xm]
,在输出到文件之前,
[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
输出在PowerShell终端中正确显示颜色(我使用了chcp
,不工作)
发布于 2017-08-16 08:50:34
你可以试试这样的方法:
... | ForEach-Object {
$_ -replace '\[\d+(;\d+)?m' | Add-Content 'C:\path\to\output.txt'
$_
}
或者将其包装在一个函数中:
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'
发布于 2019-10-09 04:52:57
对于windows系统,可以使用替换命令作为Powershell 3.0的一部分。powershell使用regex表达式来替换颜色代码。(在UNIX情况下,可以使用sed命令)
使用Regex
下面是删除ANSI颜色代码的标准Regex (可以在Linux和windows中使用)
'\x1b\[[0-9;]*m'
\x1b
(或\x1B
)是转义特殊字符。
(sed
不支持替代品\e
和\033
)\[
是转义序列的第二个字符。[0-9;]*
是颜色值regex。m
是转义序列的最后一个字符。最终指挥
我在这里将停靠程序的日志输出到日志中,file.One对其他命令也可以这样做。
docker logs container | ForEach-Object { $_ -replace '\x1b\[[0-9;]*m','' }| Out-File -FilePath .\docker-logs.log
上面的命令将从输出流中删除特殊字符,如[1;35m
、[0m[1;3
和^[[37mABC
。
https://stackoverflow.com/questions/45703539
复制相似问题