?

Log in

No account? Create an account

Fri, Jan. 30th, 2009, 04:29 pm
Redirecting stderr in PowerShell

One of my biggest pet peeves with PowerShell is that when you try to redirect stderr of some external process it adds a bunch of junk.  Here's the smallest example I can think of: 

PS E:\> C:\Python25\python.exe does_not_exist.py
C:\Python25\python.exe: can't open file 'does_not_exist.py': [Errno 2] No such file or directory

PS E:\> C:\Python25\python.exe does_not_exist.py > py.out 2>&1
PS E:\> type py.out
python.exe : C:\Python25\python.exe: can't open file 'does_not_exist.py': [Errno 2] No such file or directory
At line:1 char:23
C:\Python25\python.exe  <<<< does_not_exist.py 2>&1

where the text in orange above should not be there.  The really annoying thing about this is that PS does this for each and every line of output in stderr!  You'd think there'd be some global variable to turn this off, but alas I've been unable to find one.  While I couldn't find a workaround for this online anywhere, I was able to come up with one on my own via the add-content cmdlet:

PS E:\> C:\Python25\python.exe does_not_exist.py 2>&1 | add-content -path py_add-content.out
PS E:\> type py_add-content.out
C:\Python25\python.exe: can't open file 'does_not_exist.py': [Errno 2] No such file or directory

Mon, Oct. 3rd, 2011 05:39 am (UTC)
(Anonymous): Another work-around

It seems like you can get rid of the junk by running |%{$_.ToString()} on the output.
07:34 > C:\Python32\python.exe no.py 2>&1 | %{$_.ToString()}
C:\Python32\python.exe: can't open file 'no.py': [Errno 2] No such file or directory