What is a BAT file, how to create batch command processing files


Automation made easy

How to create a bat file? To do this you need to do the following:

  1. In any text editor, for example, Notepad or WordPad, create a text document.
  2. Write down your commands in it, starting with @echo [off], and then (each time on a new line) - title [name of the batch script], echo [message that will be displayed on the screen] and pause.
  3. Save the text in an electronic document with the .bat extension (for example, test.bat).
  4. To run, double-click on the newly created batch file.
  5. To edit it, you need to right-click on it and select “Edit” from the context menu.

The raw file will look something like this:

@echo off

title This is your first bat file script!

echo Welcome to the batch processing script!

pause

We will discuss bat file commands and their use in more detail below.

What is a BAT file?

From the point of view of a computer user, this is a text file with the appropriate extension, but for the operating system such files are special - they consist of a number of commands, which, after being launched, are interpreted and executed according to certain rules. Thus, the answer to the question of what is a batch file for a computer running Windows OS may sound like this: this is a set of commands written in text format, allowing you to save time on typing them every time the need arises. The slang name for such files is a batch file; they are also called batch files.

With the help of such batch files you can automate entire classes of tasks:

  • manage the computer file system (delete, create, move files, directories, subdirectories);
  • execute a sequence of commands with certain parameters, which may be context-sensitive;
  • carry out batch launch of programs/utilities.

Preservation

The above script displays the text “Welcome to the Batch Processing Script!” on the screen. The electronic document must be written by selecting the text editor menu item “File”, “Save As”, and then specify the desired name of the bat file. You should end it with a .bat extension (for example, welcome.bat) and click OK. To display the Cyrillic alphabet correctly, in some cases you should make sure that the encoding is selected correctly. For example, when using the console of a Russified Windows NT system, the document must be saved in CP866. Now you should double click on the bat file shortcut to activate it.

But the following message will appear on the screen:

“Welcome to the batch processing scenario! To continue, press any key..."

If the bat file does not start, users recommend going to the registry and deleting the key:

"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.BAT\UserChoice."

Don't think that's all that batch scripts can do. Script parameters are modified versions of command line commands, so the user is limited only by their capabilities. And they are quite extensive.

Basic commands, examples of using BAT files

The principle of creating a batch file is simple and clear, but the main difficulties are related to its content - without commands such a file is useless. The simplest and, by the way, most frequently used example of a command is the launch of programs that we have already discussed, or the start command. Its full syntax takes several lines, and if you wish, you can familiarize yourself with it by finding the appropriate instructions. For now, we’ll look at how you can automate the simple launch of three programs that you use in your daily work. Let it be Chrome, VLC and Total Commander.

Let's create a batch program that will sequentially launch all three programs with a five-second delay.

The body file will look like:

start "" "C:/Program Files/Google/Chrome/Application/chrome.exe"

timeout /t 05

start "" "C:/Program Files/VideoLAN/VLC/vlc.exe"

timeout /t 05

start "" "C:/Program Files/TotalCMD/totalcmd.exe"

You already know why empty quotes are needed. The timeout command with the /t parameter specifies the time interval before the next command is run.

If there were no folders with spaces in the path, they could be specified without quotes.

The standard way of executing this BAT file assumes that when executing the script, three console windows will be open, which will close automatically as soon as the command is completed. But there is a way to run start commands in one terminal window. To do this, add the /b parameter immediately after the start directive, and only then everything else.

Sometimes, to launch programs through a batch file, the user's reaction is required, that is, he must decide for himself when the next program should start. In such cases, instead of timeout, a pause directive without parameters is used, as a result of which, after starting each program, the message “Press any key to continue” will appear.

Another interesting example is a script, the launch of which will lead to shutdown or reboot of the computer. The main command will be shutdown with parameters, but there will also be a number of auxiliary directives that you need to know, because they may be useful in other cases.

An example of such a script:

@echo off chcp 1251 echo "Are you sure you want to turn off your computer?" pause shutdown /s /t 0

The first directive specifies that when commands are executed, they should not be printed to the screen. Everything is clear with the second line - we want to use Cyrillic characters. The echo command is used to display the contents of a parameter in quotes on the monitor. You also know the effect of the pause directive. Finally, the shutdown command causes the PC to shut down (if the /s option is specified) or reboot (/r) and the /t option specifies the delay in seconds before the command is executed.

In principle, to perform the main action, the fifth line is enough, without using the previous four.

Sometimes, despite the presence of the chcp 1251 directive, Cyrillic characters are displayed as clunkers. Try using ANSI encoding in such cases.

BAT files often use commands designed to work with the file system.

Thus, the del command can be used to delete folders and/or files; its analogue is the erase command. Among the parameters used, we note the following:

  • /p – indicates that before deleting a file/directory, you must answer affirmatively to the system request;
  • /f – deletes even those files that have the “read-only” attribute;
  • /s – deletes a directory along with its internal contents, all subdirectories and files;
  • /q – delete files without asking for confirmation.

A very useful command that allows you to automate the creation of backup copies of important directories by copying a folder to a specified location along with all subdirectories:

robocopy C:/data E:/backup1 /e

pause

As a result of executing the command, the data folder will be copied to the backup1 directory located on another logical drive, along with all its contents. And this command has many parameters that allow you to configure the script’s operation quite flexibly.

Computations

In bat files, you can perform simple arithmetic operations on 32-bit integers and bits using the set /a command. The maximum supported number is 2^31-1 = 2147483647, and the minimum is -(2^31) = -2147483648. The syntax is reminiscent of the C programming language. Arithmetic operators include: *, /, %, +, -. In the bat file, % (the remainder of an integer division) should be entered as “%%”.

Binary number operators interpret the number as a 32-bit sequence. These include: ~ (bitwise NOT or complement), & (AND), | (OR), ^ (exclusive OR), << (left shift), >> (right shift). The logical negation operator is ! (Exclamation point). It changes 0 to 1 and a non-zero value to 0. The combination operator is , (comma), which allows more operations to be done in a single set command. The combined assignment operators += and -= in the expressions a+=b and a-=and correspond to the expressions a=a+b and a=ab. *=, %=, /=, &=, |=, ^=, >>=, <<= work the same way. The operator precedence is as follows:

(); %+-*/; >>, <<; & ^; |; =, %=, *=, /=, +=, -=, &=, ^=, |=, <<=, >>=; ,

Literals can be entered as decimal, hexadecimal (with leading 0x), and octal numbers (with leading zero). For example, set /a n1=0xffff assigns n1 a hexadecimal value.

How to create a file with BAT extension in Windows 10/8/7

Since a batch file is a regular text file with unusual content, almost any text editor can be used to create it. Of course, you will also need to know the syntax of the command line language. Using Word is not the most optimal way; it is much easier to use Notepad, but it is even better to use Notepad++, since this editor has a useful feature - it can highlight syntax, making the task easier for users. True, it is not included in the operating system; you will have to download it.

In both cases, the creation of a batch file follows the same scenario: in the “File” menu, select “Create”, fill the file with the contents, after editing, click “Save As”, give a name to the batch file, and in the “File type” field indicate “Batch file” .

In classic Notepad, the extension must be written manually by selecting the “All files” option in the “File type” field.

When writing batch scripts, you need to consider the following nuances:

  • Line breaks in such files are not allowed; they will be interpreted incorrectly;
  • the correct encoding is UTF-8;
  • when using Cyrillic characters in commands, the encoding should be changed using the special command chcp 1251;
  • The BAT extension is identical to CMD. Files ending with this extension will be processed by the command interpreter in the same way.

There are other interesting points.

Using long names in BAT files

Many users, when practically considering the question of how to create a body file, including with the CMD extension, are faced with the problem of long names that are available in Windows. The command line interpreter in this regard has remained an inveterate retrograde - it understands file and directory names in DOS format, that is, no more than 8 characters in length. How is such a dilemma resolved?

One of the most well-known methods is to shorten the name to 6 characters (excluding spaces) and give the rest an ending consisting of a tilde character (~) and the number 1. For example, the standard name of the Program Files directory would be Progra~1, Sound Blaster folder will be named SoundB~1.

It would seem like a very elegant solution. But not in all cases. Let's say you have several folders starting with the same name. A typical example is the installation of several software products from Mozilla in the same Program Files - in this case, the abbreviated name will be Mozill, and if everyone is assigned a remainder of ~1, then this will be incorrect. The solution is to name the files by assigning a number in ascending order. We get the sequence for the Firefox, Thunderbird and Sunbird products in the form of the lines Mozill~1 for the browser, Mozill~2 for Thunderbird and Mozill~3 for the organizer.

The problem is that if one of the products is removed, for example Firefox, the remaining two entries will not work. By uninstalling Thunderbird, you will make Sunbird unavailable. Finally, this method allows you to name only nine files/folders with the same starting name. So this method cannot be called satisfactory.

The second solution is to enclose long names and paths in quotes.

Quotes in batch files

If you think that you know everything about how to make a BAT file, then you are most likely mistaken. Let's say you need to specify one of the command parameters in quotes. The quotes themselves are not prohibited by the syntax, but you always need to take into account the rules for writing a specific command. Let us need to launch the scw.exe executable. The corresponding command, in theory, should look like

start "C:\Program Files\SoundClub\scw.exe"

But this will be interpreted incorrectly by the interpreter, since in the START command syntax the optional parameter [“header”] comes first, and only then comes the path. Therefore, so that the command interpreter does not get confused, we must specify the first parameter, even if it is not needed - we simply leave it empty.

Then our team will be transformed:

start "" "C:\Program Files\SoundClub\scw.exe"

It would also be correct to enclose in brackets all names of folders/files with spaces inside. But there are situations when both options will not work. In such cases, it is advisable to use the cd command to move to the desired directory and work in the target directory. In our case, the body file will look like:

%SystemDrive% cd \Program Files\SoundClub\ start scw.exe

This method is more labor-intensive, but it is guaranteed to work.

As you can see, creating and writing BAT files, even for such simple tasks as launching programs in Windows, is largely an art.

External commands

  • Exit is used to exit the DOS console or (with the /b option) only the current bat file or routine.
  • Ipconfig is a classic console command that displays network information. It includes MAC and IP addresses, and subnet masks.
  • Ping pings an IP address, sending data packets to it to estimate its distance and latency (response). Also used to set a pause. For example, the command ping 127.0.01 –n 6 pauses code execution for 5 seconds.

The library of commands in bat files is huge. Luckily, there are many pages on the web that list them all, along with batch script variables.

Rating
( 1 rating, average 5 out of 5 )
Did you like the article? Share with friends:
For any suggestions regarding the site: [email protected]
Для любых предложений по сайту: [email protected]