batch file example: Redirect stderr and stdout through pipe
Posted by jpluimers on 2012/12/19
I knew that 2>&1 was needed to redirect both stderr and stdout, but for piping, it cannot be at the end of the line. This works in the categories shown at the bottom of the post.
Rob van der Woude again to the rescue in redirection:
(4) Redirecting both standard output and standard error to the same file or device is done by adding
2>&1to the command line. This will only work in OS/2 and NT, not in MS-DOS.
Where you put2>&1is rather critical. It will only do what it is supposed to do when placed at the end of the command line (as Jennie Walker pointed out to me) or right before the next pipe (|).
Example: batch file that checks if a few NarrowCast machines are indeed on-line and logged on with the right user.
It uses PsLoggedOn to verify who is logged on, and Explorer to show a hidden share.
The pipe is needed to verify there is indeed a domain user logged on.
@echo off for %%m in (Machine1 Machine2 Machine3) do call :show %%m goto :pause :show echo %1 %~dp0PsLoggedOn -L \\%1 2>&1 | find /I "MYDOMAIN\" start explorer /e,\\%1\NarrowCast$ goto :end :pause pause :end
–jeroen






IL said
Powershell has more ways to redirect the output http://tfl09.blogspot.ru/2014/11/capturing-different-types-of-powershell.html
jpluimers said
Cool. Can you combine those output streams like in cmd, DOS and unix/Linux?
IL said
Seems like you can do “2>&1 >$null” or “”2>&1 | Out-Null” or “[Void]$(… 2>&1)” as of this http://stackoverflow.com/questions/5260125/whats-the-better-cleaner-way-to-ignore-output-in-powershell
As of powershell get-help about_Redirection it also has Tee-Object to make the tee (:
jpluimers said
Wow. I’m impressed!