2

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

Community
  • 1
  • 1
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
  • Are you calling an external program from PowerShell that is writing to standard output? – Andy Arismendi May 18 '12 at 15:10
  • 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 May 18 '12 at 15:24

4 Answers4

2

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.

Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
1

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

[Console]::Error.WriteLine("Hello")
goric
  • 11,491
  • 7
  • 53
  • 69
1

Powershell way:

$host.ui.WriteErrorLine('Hello')

This not fill $error automatic variable.

CB.
  • 58,865
  • 9
  • 159
  • 159
1

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

BartekB
  • 8,492
  • 32
  • 33