My application should write it's errors as literal JSON objects on stderr. This is proving difficult with PowerShell (5, 6 or 7) since PowerShell seems to want to prevent you from writing to stderr and, if you do succeed, it changes what you write.
In all examples we are running the following from within a powershell/pwsh console:
./test.ps1 2> out.json
test.ps1
Write-Error '{"code": "foo"}'
out.json
[91mWrite-Error: [91m{"code": "foo"}[0m
PowerShell is changing my stderr output. Bad PowerShell.
test.ps1
$Host.UI.WriteErrorLine('{"code": "foo"}')
out.json
PowerShell not writing to stderr (or >2
is not capturing it). Bad PowerShell.
test.ps1
[Console]::Error.WriteLine('{"code": "foo"}')
out.json
PowerShell not writing to stderr (or >2
is not capturing it). Bad PowerShell.
Update
I now understand that PowerShell does not have a stderr
but rather numbered streams of which 2
corresponds to Write-Error
and [Console]::Error.WriteLine()
output and is sent to stderr of the pwsh/powershell.exe
process IFF that output is redirected.
In short, stderr
only exists outside of powershell and you can only access it via redirection:
pwsh ./test.ps1 2> out.json
Inside of powershell you can only redirect 2>
the output from Write-Error
. [Console]::Error.WriteLine()
is not captured internally but sent to the console.