Batch File Tips and Tricks

A collection of some useful snippets for batch files.

Controlling batch file output

To stop every line of the batch file being output to the command prompt put this at the top of the batch file, this makes for a less noisy output.

@echo off

Echo the output of a command, useful for logging what the batch file is actually doing.

for /f %%i in ('dir') do echo %%i

Working with variables

Store the output of a command as a variable to be used elsewhere in the batch file. Normally for /f on its own would loop the output word by word using whitespace as a delimiter, by adding tokens=* we make it loop the output line by line. Note as we're looping line by line the variable will be set to the value of the last line

for /f "tokens=*" %%i in ('cd') do set current_directory=%%i
echo %current_directory%

However there is a better way to query the current working directory than the previous example, use the built in variable %cd%.

set current_directory=%cd%

Invoking other batch files

To invoke a second batch file from inside a batch file without ending the execution when the second batch file is finished.

call other.bat

One problem with calling other batch files is that we may not be in the directory we think we are in, the batch file may have been invoked from a different directory to the one it is located in. To work around this we can wrap calls to other relative batch files with a push and pop of the current batch files directory.

pushd %~dp0
call other.bat

Or just append the current batch files directory to the relative batch file's name.

call %~dp0other.bat

Simulating functions

Another use of call is to combine it with goto and mimic the behaviour of functions within batch files.

goto post_functions

echo hello world!
exit /b 0


call :hello_world

Easier debugging

To stop the command window from closing immediately when done only after double clicking a batch file.

@echo %cmdcmdline% | findstr /l "\"\"" >NUL 2>&1
if %errorlevel% EQU 0 pause

This checks if the command line used to invoke the batch file was a call to explorer, %cmdcmdline% would look something like C:\Windows\system32\cmd.exe /c ""D:\example.bat" ". This code above looks for the double quotes just before the file path.