Redirecting Output from within Batch file Redirecting Output from within Batch file windows windows

Redirecting Output from within Batch file


The simple naive way that is slow because it opens and positions the file pointer to End-Of-File multiple times.

@echo offcommand1 >output.txtcommand2 >>output.txt...commandN >>output.txt

A better way - easier to write, and faster because the file is opened and positioned only once.

@echo off>output.txt (  command1  command2  ...  commandN)

Another good and fast way that only opens and positions the file once

@echo offcall :sub >output.txtexit /b:subcommand1command2...commandN

Edit 2020-04-17

Every now and then you may want to repeatedly write to two or more files. You might also want different messages on the screen. It is still possible to to do this efficiently by redirecting to undefined handles outside a parenthesized block or subroutine, and then use the & notation to reference the already opened files.

call :sub 9>File1.txt 8>File2.txtexit /b:subecho Screen message 1>&9 echo File 1 message 1>&8 echo File 2 message 1echo Screen message 2>&9 echo File 1 message 2>&8 echo File 2 message 2exit /b

I chose to use handles 9 and 8 in reverse order because that way is more likely to avoid potential permanent redirection due to a Microsoft redirection implementation design flaw when performing multiple redirections on the same command. It is highly unlikely, but even that approach could expose the bug if you try hard enough. If you stage the redirection than you are guaranteed to avoid the problem.

3>File1.txt ( 4>File2.txt call :sub)exit /b:subetc.


if you want both out and err streams redirected

dir >> a.txt 2>&1


I know this is an older post, but someone will stumble across it in a Google search and it also looks like some questions the OP asked in comments weren't specifically addressed. Also, please go easy on me since this is my first answer posted on SO. :)

To redirect the output to a file using a dynamically generated file name, my go-to (read: quick & dirty) approach is the second solution offered by @dbenham. So for example, this:

@echo off> filename_prefix-%DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log (echo Your Name Hereecho Beginning Date/Time: %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.logREM do some stuff hereecho Your Name Hereecho Ending Date/Time: %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log)

Will create a file like what you see in this screenshot of the file in the target directory

That will contain this output:

Your Name HereBeginning Date/Time: 2016-09-16_141048.logYour Name HereEnding Date/Time: 2016-09-16_141048.log

Also keep in mind that this solution is locale-dependent, so be careful how/when you use it.