Redirect that Error

 

Redirecting Errors | Admin ArsenalWhen writing batch files, it’s common to spit the output of a command to a file using the redirect operator.

C:\> somecommand.exe > output.txt

For some commands this doesn’t work correctly and you don’t get all of their output. You can see an example by using the dir command.
C:\> dir aa: > out.txt

In this case, the error message doesn’t go into out.txt, it still gets written to the console. Why is this?

All command line programs have two channels of communication with the console. One is called “standard output” and the other is “standard error.” Typically data goes to standard output and error messages go to standard error. In the example above the data went to out.txt but the error message went to the console. There is a special version of the redirect operator for the standard error channel:
C:\> dir aa: > out.txt 2> error.txt

Now the error message gets written to the error.txt file and nothing goes to the console. But what if you want both channels to go to the same file, just as they would normally go to the console? You can’t use the same file name for both channels, you need to use a special file name for the error redirect:

C:\> dir aa: > out.txt 2>&1

This tells the error channel to write to the same file as the standard output. For the sake of completeness, you can reverse the files:

C:\> dir aa: 2> out.txt >&2

Hopefully this little tip will make all of your batch writing more fun (and you thought it was already as fun as it was going to get!)