2
votes

In Powershell, how do I redirect standard output to standard error?

I know I can do the converse with 2>&1 so I tried:

echo "Hello" 1>&2

but I get a silly error The '1>&2' operator is reserved for future use.

I ask because being able to do this would make it easier for me to debug another problem. See $LastExitCode=0 but $?=False in PowerShell. Redirecting stderr to stdout gives NativeCommandError

4
Are you calling an external program from PowerShell that is writing to standard output?Andy Arismendi
So why not just capture it's output and treat it as if it was written to standard error? $output = & externalprog.exe 2>&1. The variable stores the output that you want to be sent to standard error.Andy Arismendi

4 Answers

2
votes

Alas, it's not possible to redirect standard output to standard error. I think that's an unfortunate omission. Let's hope this is fixed in a future version of Powershell.

1
votes

Assuming you are in full control of the messages, you could tap into .NET to help out with this:

[Console]::Error.WriteLine("Hello")
1
votes

Powershell way:

$host.ui.WriteErrorLine('Hello')

This not fill $error automatic variable.

1
votes

First: there is nothing silly with error you get. In v3 e.g. we got some additional redirection option and eventually I guess we will be able to redirect verbose to warning, debug to error, and output to error, as you needed.

Before that will happen you can try to emulate this behavior, at least for output. Not sure if that will solve your issues, but you can:

echo "foo" | Write-Error
yourproram.exe | Write-Error

HTH Bartek