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

394 views Asked by At

Hello I have the following test code in powershell 7.1 and 7.2 preview.

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. The write-error output shows weird characters.

Lalala

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

Test Testt

Information Information

When I do the same in powershell 5 the results are as I expect them to be:

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

Is there anything going on with powershell core that causes this behavior and is there a way to fix it?

1

There are 1 answers

0
zett42 On BEST ANSWER

This behaviour seems to be caused by the new error view mode, which can be changed through the $ErrorView preference variable.

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). The escape codes make only sense for console output, where they colorize the 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':

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

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

GitHub issue