【问题标题】:Write-error gives weird characters when redirecting to a file in powershell core重定向到 powershell 核心中的文件时,写入错误会给出奇怪的字符
【发布时间】:2021-04-27 08:33:48
【问题描述】:

您好,我在 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 

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

拉拉拉

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

测试测试t

信息信息

当我在 powershell 5 中执行相同操作时,结果与我预期的一样:

拉拉拉

C:\Users\MoonChild\Documents\huh.ps1 :这是一个测试 + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,huh.ps1

测试测试t

信息信息

powershell 内核有什么问题会导致这种行为吗?有没有办法解决它?

【问题讨论】:

    标签: powershell file redirect output write-error


    【解决方案1】:

    此行为似乎是新的错误查看模式引起的,可以通过$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
    

    输出:

    写入错误“这是一个测试” 2>&1 > C:\Temp\test.txt :这是一个测试 + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId:Microsoft.PowerShell.Commands.WriteErrorException

    相关问题: Capture a literal string on stderr in powershell

    GitHub issue

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多