简体   繁体   English

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

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

Hello I have the following test code in powershell 7.1 and 7.2 preview.您好我在 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 

This results in the following output in the file.这会导致文件中出现以下 output。 The write-error output shows weird characters.写入错误 output 显示奇怪的字符。

Lalala拉拉拉

[91mWrite-Error: [91mThis is a test[0m [91mWrite-Error: [91m这是一个测试[0m

Test Testt测试测试

Information Information资讯资讯

When I do the same in powershell 5 the results are as I expect them to be:当我在 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 C:\Users\MoonChild\Documents\huh.ps1: 这是一个测试 + CategoryInfo: NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId: Microsoft.PowerShell.Commands.WriteErrorException,呵呵。

Test Testt测试测试

Information Information资讯资讯

Is there anything going on with powershell core that causes this behavior and is there a way to fix it? powershell 内核有什么问题会导致这种行为吗?有没有办法解决它?

This behaviour seems to be caused by the new error view mode , which can be changed through the $ErrorView preference variable .这种行为似乎是由新的错误视图模式引起的,可以通过$ErrorView首选项变量进行更改。

The default for $ErrorView is ConciseView which outputs ANSI escape codes to the file (this is what you see as ▯[91m and ▯[0m - the rectangle is the non-printable ESC character). $ErrorView的默认值是ConciseView ,它将 ANSI 转义码输出到文件(这是您看到的▯[91m▯[0m - 矩形是不可打印的 ESC 字符)。 The escape codes make only sense for console output, where they colorize the output.转义码仅对控制台 output 有意义,它们在其中为 output 着色。 They don't make much sense when redirecting to a file, so this appears like a bug to me.重定向到文件时它们没有多大意义,所以这对我来说似乎是一个错误。

To get the PS 5 behaviour, set $ErrorView = 'NormalView' :要获得 PS 5 的行为,请设置$ErrorView = 'NormalView'

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

Output: Output:

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

Related question: Capture a literal string on stderr in powershell相关问题:在 powershell 中的 stderr 上捕获文字字符串

GitHub issue GitHub 问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM