Programming Field

About batch files - DOS/Command Prompt Reference

A batch file refers to a file that contains a series of commands written for input at the prompt. It is also known as a batch program. By using batch files to sequentially execute commands, you can provide functionality similar to application programs.

The extension for batch files has been ‘.bat’ since MS-DOS, and in Windows NT series, you can also use ‘.cmd’. ‘.cmd’ is also referred to as a Command Script, but there is no difference in the commands that can be executed between ‘.bat’ and ‘.cmd’.

How to make a batch file

As mentioned earlier, a batch file is a text file that contains a series of commands. By writing one or more commands per line, you can create a sequence of commands. For example, if you input the following content in a text editor and save it as a file named ‘simple.bat’ (without adding any suffix like ‘.txt’), ‘simple.bat’ becomes a batch file and can be executed.

@echo off
echo This is a batch file.
pause

After saving as ‘simple.bat’, you can either directly input ‘simple.bat’ on the prompt and press Enter to execute it or double-click on ‘simple.bat’ in Explorer to run it. By executing it,

This is a batch file.
Press any key to continue . . . 

The above-described output will be displayed, and it will enter a waiting state for input. This is the result of automatically (sequentially) executing the following processes.

  1. By using ‘@echo off’, it turns off the echo (such as ‘C:\>’) (* ‘@’ suppresses the echo of the command when placed before it. Here, without ‘@’, the command ‘echo off’ would be visible on the screen.)
  2. By using ‘echo This is a batch file.’, it outputs ‘This is a batch file.’ to the screen.
  3. By using ‘pause’, it outputs the system message ‘Press any key to continue . . . ’ and puts it in a waiting state for input.

Note that after waiting for input with Pause and entering any key, it will proceed to the next step. However, since ‘simple.bat’ does not have any further commands written, the execution will end at that point.

* A process that collectively executes a series of commands is generally referred to as ‘batch processing’ (‘batch file’ means a file that performs batch processing).

Using batch file

Batch files are often used when there is a desire to simplify a process. For example, if you need to perform a series of operations like ‘execute CmdA on file X, then execute CmdB on a specific file generated as a result’, and you need to do this multiple times, you can write the entire sequence of operations as a batch file like followings. By doing so, you can execute the entire process simply by running the batch file.

@echo off
set TEMP_X=%1
set TEMP_Y=output.tmp
CmdA %TEMP_X% %TEMP_Y%
if exist %TEMP_Y% CmdB %TEMP_Y%
if exist %TEMP_Y% del %TEMP_Y%
set TEMP_X=
set TEMP_Y=

* When writing batch files for the Command Prompt, it is recommended to enclose file names with spaces using ‘" "’ to account for the possibility of spaces in the names. For example, you can modify it as follows (this is not a complete rewrite).

@echo off
set "TEMP_X=%~f1"
set "TEMP_Y=%~dp1output.tmp"
CmdA "%TEMP_X%" "%TEMP_Y%"
if exist "%TEMP_Y%" CmdB "%TEMP_Y%"
if exist "%TEMP_Y%" del "%TEMP_Y%"
set TEMP_X=
set TEMP_Y=

When dealing with multiple commands, there are situations where you only want to execute a program or command under specific conditions. As mentioned in the above example, you can use If command or similar constructs to automatically control such processes based on specific conditions.

Batch file tips

Calling other batch files

By using the Call command, you can execute another batch file from within a batch file. This allows you to consolidate common processes into one batch file in situations where multiple batch files exist. It helps reduce the size of individual batch files and makes them easier to maintain.

As a point to note, when you execute a batch file without using the Call command, the original batch file will end its processing at that point. When running a batch file from within another batch file, it's essential to be aware of this behavior and, in most cases, use Call to ensure the execution continues as expected.

Calling by drag and drop

In Windows, when creating a batch file, you can drag and drop any file onto the batch file in Explorer, similar to other applications (executable files).

In this case, the batch file is executed with the full path (absolute path) of the dropped file specified as an argument. This eliminates the need to manually input the file name from the command prompt when executing the batch file with arguments.

Furthermore, by creating a shortcut for the batch file and adding the arguments that the batch file parses in the ‘Target’ field of the shortcut, dropping a file onto the shortcut will execute the batch file with the combined arguments of the ‘pre-added arguments’ and the ‘path of the dropped file’.

Setting environment variables

Environment variables are a type of ‘setting’ that can be used by programs and batch files. When a program needs to reference a specific environment variable, batch files can be used to change the content of that environment variable as needed.

Specifically, you can write a batch file that sets environment variables using the Set command, and then write the process to execute the program afterward. The content of the environment variables set in the batch file will be reflected in the program. Since the settings made here overwrite system settings, you can typically run programs directly to use system settings. However, you can use a batch file to execute a program and change its behavior conditionally when specific conditions are met.

Scheduling a batch file periodically

If you want to execute a series of commands periodically, you can create a batch file and register it as a task to be executed. To register the task, you can use the Task Scheduler or the Schtasks command.

When scheduling periodic execution, it's important to consider the user privileges that the batch file will utilize, such as whether it will run as a specific user or even if it will run when no user is logged in. For tasks requiring special permissions like Robocopy, ensure to set appropriate permissions when registering the task. When using ‘Schtasks /Create’, you can use options like ‘/RU’ and ‘/RL’ to specify the user and privileges, respectively.

Popular commands/characters used in batch files

The following commands and characters are commonly used for controlling batch files and similar purposes (in alphabetical order):

CallExecutes a batch program from a batch program without terminating. Or executes subroutines.
ChoiceDisplays choices on the screen and prompts for input.
ClsClears all output in the screen.
ColorChanges the prompt color.
EchoOutputs text to the screen. Also toggles prompt display.
EndlocalEnds localization of environment changes.
ExitExits the prompt, batch programs, or subroutines.
ForExecutes a command for each files or texts matching with the specified pattern.
GotoMoves execution to the specified label in batch files.
IfExecutes a command when specified condition is met.
PathDisplays or changes the path(s) to search for programs.
PauseStops (pauses) the execution and prompts for any key input.
PopdRestores Pushd's directory change just before.
PromptSets/changes the prompt display.
PushdChanges the current directory. The current directory can be restored by calling Popd.
RemDoes nothing. Used for writing comments in batch files.
SetDisplays or modifies environment variables.
SetlocalBegins localization of environment changes, making environment variable changes or etc. temporary.
Start commandLaunches the program or executes the default processing for the file.
TitleChanges the title of the prompt window.
|[Pipe] Passes the output of the left command as input to the right command.
<[Input redirection] Passes specified file contents as input to the command.
>[Output redirection] Writes the output of the command to the specified file.
>>[Append redirection] Appends the output of the command to the specified file.
@Suppresses echo-back of commands in batch files.
:Defines a label in batch files.
%Used to retrieve values of environment variables and batch program parameters.
!Used for the delayed environment variable expansion.
^Treats the following character as a regular character. Or treats multiple lines as one-line command line.
&Executes two or more commands in a row.
||Used to execute the another command when the command fails.
&&Used to execute the another command when the command succeeds.
( )Treats multiple commands like one command.

Batch file notes

  • A batch file (command script) is treated as one of the ‘executable files’ by the operating system (OS). Therefore, it can be directly executed by entering the file name on the command prompt. Furthermore, it is possible to execute a batch file directly from applications/programs outside the command prompt (for example, specifying a batch file as the program to be executed by the CreateProcess function in Win32API).
  • The content of a batch file consists of text data with commands written on each line. Therefore, you can create and edit a batch file using standard text editors such as Notepad.
    • When saving a file in a text editor, explicitly specifying the extension as ‘.bat’ or ‘.cmd’ (Windows NT series/XP and later) will create a batch file.
  • Batch files are generally executed on the command prompt screen (strictly speaking, in an environment with console or equivalent input/output). If executed from applications that inherently lack a command prompt screen, such as GUI applications in Windows, a new command prompt screen is usually displayed unless there are specific instructions or handling, and the batch file is executed on that screen.
  • A batch file is fundamentally a file designed to execute a sequence of commands. Therefore, it is not well-suited for tasks that involve operations beyond command and program execution, such as reading data from a specific offset within a file or performing complex text data processing.
    • In cases where such operations are required, it is advisable to use PowerShell, various scripting languages (such as JScript (JavaScript) or VBScript through Windows Script, JavaScript using Node.js, Ruby, Python, etc., with Windows support), or develop a client program using languages like C or .NET.