# How can I launch batch files from another batch file while piping their output and retaining the current working directory?

I have a batch file which runs as a scheduled task. For the sake of example lets call it alltasks.bat.

It looks like the following:

@ECHO OFF
clearwebtemp.bat > clearwebtemp_out.txt
clearblahtemp.bat > clearblahtemp_out.txt
clearblihtemp.bat > clearblihtemp_out.txt


This works fine when none of the called scripts change directories, but if they do then the main script fails to complete the remaining batch calls or pipe the output to the files.

I tried using the start command, but that predictably piped the output of the start command rather than that of the batch file itself.

I also tried retaining the current working directory using the %CD% variable at the top of the script and then switching back to it after each call, but the piping out to the file was done inside the directory that the script switched to, which didn't seem to make sense.

Is there an obvious (or not-so-obvious) way to achieve what I'm attempting to accomplish?

• How are you switching directories? Are you using the /d option with chdir? Aug 22, 2012 at 16:46
• I am. chdir /d %OLDDIR% Aug 22, 2012 at 16:53
• Why not simply allow the scripts to change the current directory and call them by an absolute path instead, possibly containing the starting directory as a variable, i.e.: "%mydir%\foo.bat > %mydir%\bar.txt"? Aug 22, 2012 at 17:17

This should do what you're asking for:

cmd /c clearwebtemp.bat > clearwebtemp_out.txt
cmd /c clearblahtemp.bat > clearblahtemp_out.txt
cmd /c clearblihtemp.bat > clearblihtemp_out.txt


Another Solution:

@ECHO OFF
pushd .
call clearwebtemp.bat > clearwebtemp_out.txt
popd
pushd .
call clearblahtemp.bat > clearblahtemp_out.txt
popd
pushd .
call clearblihtemp.bat > clearblihtemp_out.txt


or

@ECHO OFF
call clearwebtemp.bat > clearwebtemp_out.txt
%~d0
cd %~p0
call clearblahtemp.bat > clearblahtemp_out.txt
%~d0
cd %~p0
call clearblihtemp.bat > clearblihtemp_out.txt


You can ignore the %~d0 if your bats :) stay on the same drive.

You can do this using cmd /c "for command" in loop:

@cmd /q /s /c "for %%i in (web,blah,blih)do "clear%%~itemp.bat" > "clear%%~itemp_out.txt""
clear+ web  +temp.bat > clear+ web  + temp_out.txt
clear+ blah +temp.bat > clear+ blah + temp_out.txt
clear+ blih +temp.bat > clear+ blih + temp_out.txt
@cmd /q /s /c "for ( web, blah, blih ) +  "clear + %%~i + temp.cmd"  > "clear + %%~i + temp_out.txt""
• To call and wait for each to run before calling the next, use call file.bat:
@cmd /q /s /c "for %%i in (web,blah,blih)do call "clear%%~itemp.bat" > "clear%%~itemp_out.txt""