Sign In
Sign In

How to Create and Use Batch Files

How to Create and Use Batch Files
Hostman Team
Technical writer
Windows
22.04.2024
Reading time: 7 min

Batch files are text files with .BAT or .CMD extensions that store a set of commands and execute them in the operating system terminal. Such files are necessary to automate standard user work in Windows. 

Batch files can be considered a Windows alternative to the Unix shell scripts which you would run on a Linux server.

This article will describe in detail how to create, configure and run bat files in Windows and which commands to use.

Prerequisites

  • A cloud server or a personal computer with the Windows operating system installed.

  • Notepad or another text editor. We recommend using editors with built-in syntax highlighting, for example, Notepad++.

Create a batch file

To create a Windows bat file, open any text editor and fill it with some content. 

As an example, let's create a batch file that will display the message "Hello, user!" in the Command Prompt window:

@echo off
echo Hello, user!
pause

Now, you need to save the file using the .bat extension. To do this, go to FileSave as….

If you are using Notepad++, select Batch file in the Save as type field and enter the file name.

Image1

When using Notepad, select All files as the file type and enter your file name and extension.

04044ffa Ee06 4954 B80f E44718b2bc0e

If you saved the file with the wrong extension, it can be easily fixed by renaming the file and specifying the correct extension. 

To do this, you need to enable showing file extensions in the Explorer's View tab.

Image6

Syntax of a batch file

Below is a list of basic rules that you need to know when using Windows bat scripting:

  • Each command must be entered on a new line.

  • The commands specified in the file are executed strictly in order, from first to last. The exception is those cases when a transition from one part to another is organized inside the file (for example, goto).

  • Indicate directories in quotes to minimize errors.

  • Add |Y| before commands that require confirmation (such as del or format).

  • You can use two types of commands: internal (built-in) and external. The first are the commands of the Command Prompt (cmd.exe) itself (we'll talk about them later). The second type includes all possible executable files (extensions .EXE, .CMD or .BAT).

  • Use @echo off at the beginning of the file to disable displaying the command line after running the batch file.

Run a batch file

To run a bat file in Windows, simply double-click on it.

It is worth considering that some batch files may contain commands that require administrator rights. In that case, right-click on the file and select Run as administrator

However, if running the file implies some kind of system output, you should run it using the Command Prompt.

To launch the Command Prompt, press WIN+R, enter cmd in the input field, and press Enter. A command line window will open, into which you need to drag-and-drop the batch file and press Enter.

The batch file will begin executing commands and display the result.

Let's run the test file that we created in the previous step and look at the result. If everything works correctly, you will see the message from the file: "Hello, user!".

Image5

Automate .BAT files with Task Scheduler 

A useful feature when working with batch files is the ability to run them at certain intervals. To implement this, you will need to use Task Scheduler, a built-in Windows tool.

  1. Press WIN+R, enter taskschd.msc in the input field and press Enter.

  2. Select Create Basic Task... in the Actions menu on the right. 

  3. After this, the Create Basic Task Wizard window will open, where you need to fill out four tabs:

    • Create a Basic Task. Enter the name and description of the task and click Next.

    • Trigger. Specify how often the batch file should be run and at what time.

    • Action. Select Start a program, click Next and specify the path to the batch file.

    • Finish. Check all entered data and click Finish.

Image3

The batch file is now added to the Windows schedule and will be run automatically according to your settings.

Add comments to batch files

When necessary, you can also add comments to .BAT files in Windows.

There are three ways to leave comments while writing a batch file:

  • rem. Enter the comment immediately after it:

rem your_comment_here
  • Double colon. Works similar to the rem command.

:: your_comment_here
  • goto. This one is used not only for commenting, but also for moving to another part of the batch file. After entering the command, indicate a label (in the example below it is start).

goto start
your_comment_here
:start

Each comment must have its own unique tag.

Basic commands for .BAT files

Below are the main commands used when writing a batch file.

Command

Argument

Description

cd

Catalogue

Going to the specified directory (empty argument returns the current directory).

pause

-

Pausing a batch file.

start

File path/command

Executing the specified program or command in a separate window.

md

Catalogue

Creating a directory.

copy

Path to source files and destination directory

Copying one or more files to a specified directory.

del

File or directory name

Deleting one or more files.

call

Path to the file to run

Running a batch file from another batch file.

title

Title

Changing the window title.

move

Source and destination path to file/files

Moving one file or group of files from one directory to another.

color

Background and text color (set by number or letter)

Changing the background and text color 

exit

-

Terminating the batch file.

This is not a complete list. To check all the commands, write help in the Command Prompt.

Image4

Variables

You can also use variables when writing a batch file.

To add a variable, use the set command. First, enter set, then the variable name, then its value. If you need to access a variable and read its value, add the % symbol on both sides of the variable name.

For example: 

@echo off
set example=Hello, user!
echo %example%
pause

Please note that there are no spaces before or after the equal sign, otherwise the program will not work. 

When you run the batch file with this content, the system will output "Hello, user!".

Also, when declaring a variable, you can use the /a flag, which allows to assign a number to the variable. For example:

@echo off
set /a example=2*3
echo %example%
pause

Without the flag, the entire string after the equal sign is assigned to the variable. When run, the program will output the number 6.

In addition to regular variables, there are argument variables. These variables are assigned values that are passed when the batch file is exported. They look like this: %1, %2, %3, etc.

Here's an example:

@echo off
@echo First argument variables - : %1
@echo Second argument variables - : %2
@echo Third argument variables - : %3
pause

When running this batch file, we will pass the string "Hello, user!" The result will be shown in the picture below.

Batch file example: removing unnecessary files

While working, we often end up with unnecessary files that need to be cleaned. A correctly written batch file does an excellent job of this.

Suppose you have a lot of .TXT files in a certain directory and its subdirectories that you no longer need. Let's create a simple batch file for this case:

@echo off
del /f /s /q C:\path_to_directory\Example\*.txt

Let's look at how each flag works:

  • /f allows you to delete all files (even the read-only ones).
  • /s allows you to delete files not only from the directory but also its subdirectories.
  • /q removes confirmation of file deletion.

Now, to test this batch file, let's create the Example directory and the ExampleWithTXT subdirectory, and then add three .TXT files to both:

mkdir Example
cd Example
mkdir ExampleWithTXT
notepad Example1.txt
notepad Example2.txt
notepad Example3.txt
cd ExampleWithTXT
copy C:\path_to_directory\Example\*.txt

Now, drag-and-drop the batch file to the Command Propmpt window and look at the result. The output must show that all six files were successfully removed from the Example directory and the ExampleWithTXT subdirectory.

Image7

Conclusion

In this guide, we described in detail how to create and use .BAT files in Windows and provided basic commands for working with them. Following this tutorial, you can create your first Windows bat script to automate working with the Windows OS.

Windows
22.04.2024
Reading time: 7 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us
Hostman's Support