重定向到 powershell core 中的文件时,写错误给出奇怪的字符

Write-error gives weird characters when redirecting to a file in powershell core

您好,我在 powershell 7.1 和 7.2 预览版中有以下测试代码。

Write-Output "Lalala" 1> C:\Temp\test.txt 
Write-Error "This is a test" 2>&1 >> C:\Temp\test.txt 
Write-Warning "Test Testt" 3>&1 >> C:\Temp\test.txt 
Write-Information "Information Information" 6>&1 >> C:\Temp\test.txt 

这会在文件中产生以下输出。写入错误输出显示奇怪的字符。

Lalala

[91mWrite-Error: [91mThis is a test[0m

Test Testt

Information Information

当我在 powershell 5 中执行相同操作时,结果如我所料:

Lalala

C:\Users\MoonChild\Documents\huh.ps1 : This is a test + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,huh.ps1

Test Testt

Information Information

powershell 核心是否有任何问题导致此行为,是否有解决方法?

此行为似乎是由新的 错误视图模式 引起的,可以通过 $ErrorView preference variable.

更改

$ErrorView 的默认值是 ConciseView,它将 ANSI 转义码输出到文件(这就是您看到的 ▯[91m▯[0m - 矩形是不可打印的 ESC 字符)。转义码只对控制台输出有意义,它们会在输出中着色。它们在重定向到文件时没有多大意义,所以这对我来说像是一个错误。

要获得 PS 5 行为,请设置 $ErrorView = 'NormalView':

$ErrorView = 'NormalView'
Write-Error "This is a test" 2>&1 >> C:\Temp\test.txt

输出:

Write-Error "This is a test" 2>&1 > C:\Temp\test.txt  : This is a test
+ CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

相关问题:

GitHub issue