What to write in the bat file. How to export the registry from a batch file

Now it's time to consider bat commands. Basically, commands entered into cmd are used here, but there are also some that make no sense to use on the command line.

How to get a complete list of bat commands

To describe all commands you will need to write a whole series articles, so as not to overburden you, we will limit ourselves to one article and consider compact information. As you know, the bat file and cmd commands are the same to get a list of them or . Enter the help command, which in English is written as help, press Enter. As a result, the computer will write all commands in the cmd interface with brief description.

After reviewing this list, you will want to find out in more detail what a specific bat command is. For example, let's select the for command, to describe it we will enter help for or for /? and click enter. As a result, you will receive online help for the command; it is voluminous, so you will need to press any key several times to read the subsequent description. This way you can learn the syntax of a particular command.

bat file commands

Now let's get acquainted with the commands used in the batch file, with a brief description. They are not case sensitive, however, We have listed them in uppercase to help with identification.

@ All commands executed by bat are displayed on the screen, to remove unnecessary things, a “dog” is placed in front of the command. Often used with @echo off.
setSets variables. For example, setper=c:\windows here per assigns the path. You can write a cumbersome value to a variable and specify it in the script, which makes the code more compact. If its content changes, then you will not have to change the values ​​everywhere where this variable is provided.
:: One of two commenting methods in bat file without printing this line to the screen.
:LABELWhen you add a colon to a word, it creates a label that allows you to jump to different sections batch file. A label can have a different name, LABEL is an example.
CALLBat command calling one batch file within another. All parameters described in one of the files can be passed to each other.
CHOICESelect command.
CLSClears the shell contents that are displayed above the CLS.
ECHODisplays a message on the screen. For example, "ECHO Hello!" will display "Hello!" If you don't use @ECHO off at the beginning of the batch file, then you will see the path to the bat file and two messages, which is unnecessary. You can create an empty line by typing ECHO. with a period at the end.
EXITEnds the current batch script.
GOTO LABELUsed to jump to a specific label in in this case to LABEL and executes the script after it.
IFAs in the bat programming languages, the if command represents the fulfillment of a condition, depending on which the script will go along one path or another. Please refer to the help for the syntax.
forA loop used to organize the execution of the same actions.
PAUSEIf you need to see the output of a script and it runs and the window closes quickly, then use PAUSE. It will allow you to view the result and complete the script by pressing any button.
R.E.M.Second way to comment. Unlike:: is printed on the screen if there is no @ECHO off construct.
SHIFTChanges the position of batch parameters in the bat file.
STARTLaunches programs, windows, etc. Has many attributes (see help).

This is bat basis commands The syntax of some elements is difficult for beginners and requires certain knowledge. All bat file commands, described above, are considered superficially, in order to find out their purpose, and you will find the full syntax in Windows Help.

Running a batch file is carried out in the same way as launching a regular executable program of type .COM or .EXE, that is, you specify the file name and, if required, parameters.

Example running the START batch file:

C:\>start

Role batch files special. They serve to organize convenient interaction between users and application software systems. A batch file, unlike ordinary executable programs, does not contain machine code for programs, but text that is interpreted by the DOS command processor. Lines of this text can be:

Built-in DOS commands;

Calls to executable programs;
- calls to other batch files;
- special commands to control output to the screen;
- special commands for organizing branches and cycles;
- tags.

All of these constructs, with the exception of labels, can be considered DOS commands.

DOS batch files may contain , designed to create non-trivial control sequences.

An important property of batch files is the ability to specify formal parameters in their texts. Formal parameters %1 - %9 can be used in batch files.

Consider the action special teams, allowing you to control the interpretation of command files. These, as indicated, include the commands , , , , as well as the EXIT command, which plays a special role when recursively (nested) calling command files.

GOTO command allows you to transfer control to the label and thereby re-execute sections of the command file or, conversely, bypass some sections (this makes sense in combination with the IF branch command).

Example. Let the command file PR.BAT look like:

Echo off
:m1
echo Outputting file %1 to printer
echo To stop, press CTRL-C
copy %1 prn
pause
goto m1

IN in this example the second line contains label m1 (the sign of a label is a colon at the beginning of the line), and the last line contains a command to move to this label. Four commands inside the repeatable section of the command file are used to display explanatory messages on the screen (ECHO commands) and copy to the printer a file whose name is substituted for the formal parameter %1. The PAUSE command pauses execution so that the user can look around and interrupt or continue working.

Let's say the user gives the command from the terminal:

A:\>pr docum.doc

The cyclic execution of the PR.BAT file begins with the actual parameter DOCUM.DOC. Copies of this text file will begin to be output to the printer one after another, interrupted by pauses after each copy. The user can interrupt the execution of this command file by pressing the CTRL-C keys simultaneously.

FOR command provides cyclic execution of DOS commands. In this case, you can specify a formal parameter and a list actual parameters(usually file names), which are sequentially substituted instead of a formal parameter in the text of the executable command.

Let there be a need to systematically copy the files PROG.PAS PROG.OBJ and PROG.EXE from the working directory to virtual disk E:. For this purpose, you can issue the command in the appropriate batch file:

For %%A in (PAS OBJ EXE) do copy PROG.%%A e:

Here the formal parameter %%A is sequentially mapped to the list of actual parameters in parentheses and is used in the COPY command, which in this case will work 3 times in a row.

Substituting as the second argument COPY commands instead of the name E: another formal parameter %1, it will be possible to change the copying destination by specifying it from the terminal.

Two consecutive % signs must precede a formal parameter only in batch files. When using the FOR command directly from the terminal, a single % sign is used.

Usage GUI in operating systems today seems to be something taken for granted and completely natural, but this was not always the case. First operating system MS DOS developed by Microsoft, did not have a GUI, and was controlled by input text commands. Almost 40 years have passed since then, however scripting language command line is still popular, and not only among developers.

The command line is not so convenient, but with its help you can perform operations that are not possible from the GUI. On the other hand, launching the console every time, entering commands into it one after another - all this greatly slows down the work. However, you can significantly simplify the task by creating a bat file or simply a batch file - text file with the BAT extension, containing a list of instructions processed command interpreter CMD. Such files are used for automation different tasks, for example, to delete temporary files on a schedule or run programs.

How to create a file with a BAT extension

So, how to create a bat file in Windows 7/10? Very simple. For this you will need any text editor and knowledge of command line basics. You can use Notepad, or even better, Notepad++, since the latter has syntax highlighting. Create in the editor new file, in the “File” menu, select “Save As”, give the future script a name, and in the “File Type” drop-down list, select “Batch file (*bat; *cmd; *nt)”.

If you want to use Notepad to create a bat file, you need to assign the extension manually, and select “All files” in the “File type” list.

As you can see, creating a file with the bat extension is not difficult; however, there are some subtleties here. Line breaks cannot be used in command files; the encoding of the bat file must be set to UTF-8; if the body of the script uses Cyrillic, the encoding must be changed by inserting the chcp 1251 command in the appropriate place.

Instead of the BAT extension, you can use CMD, the result of executing the script will be exactly the same.

Basic commands, syntax and examples of using batch files

You know how to make a bat file, now it’s time for the most interesting part, namely the syntax of the CMD interpreter language. It is clear that an empty batch file will not work, it will not even launch when you double click on it. For the script to work, at least one command must be written in it. For clear example Let's see how to write a bat file to launch programs. Let's say that when you start working, you launch three programs every time - Chrome, Firefox and VLC. Let's simplify the task by creating a script that will launch these programs itself at intervals of five seconds.

Open an empty batch file and paste the following commands into it:

Start "" "C:/Program Files/Google/Chrome/Application/chrome.exe" timeout /t 05 start "" "C:/Program Files/Mozilla Firefox/firefox.exe" timeout /t 05 start "" "C :/Program Files/VideoLAN/VLC/vlc.exe"

Team start runs the executable file the desired program, and the team timeout/t sets the interval between starts. Pay attention to the placement of the quotes - they contain paths that contain spaces. Also if on the way there is Cyrillic characters, at the beginning of the script you should insert a command that changes the encoding chcp 1251, otherwise the interpreter will not be able to read the path correctly.

When you run the script, four console windows will be opened sequentially; this is normal; after executing the commands, they will all automatically close, however, you can make sure that only the first window opens. To do this, the application launch code should be changed as follows:

Start /b "" "path"

It may also happen that at some point it will be necessary to pause the execution of the script so that the user can decide whether to execute all other commands or not. There is a command for this pause. Try replacing timeout with it and see what happens.

Start /b "" "path" pause

Let's look at another example of commands for a bat file. Let's write a script that will turn off the computer in one case, and restart it in another. For these purposes we will use the command shutdown with parameters /s, /r And /t. If you wish, you can add a request to perform an action to your body file, like this:

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

Let's explain. The first command hides the text of the commands themselves, the second - sets the Cyrillic encoding, the third - displays a message for the user, the fourth - sets a pause, the fifth - turns off, and with the key /r instead of /s reboots the computer without the traditional one minute delay. If you don’t want to stand on ceremony with requests and pauses, you can leave only the fifth command.

If instead of Russian text when executing the command you see kryakozyabra, try converting the script file to ANSI.

What else can you do with scripts? A lot of things, for example, deleting, copying or moving files. Let's say you have a certain data folder in the root of drive D, the contents of which need to be cleared in one fell swoop. Open the batch file and paste the following command into it:

Del /A /F /Q "D:/data"

Or you can do this:

Forfiles /p "D:/data" /s /m *.* /c "cmd /c Del @path"

Unlike the first, the second command deletes files recursively, that is, all files in the data folder will be deleted plus those located in subdirectories.

And here's another one useful example. Let's write a script that will create backup copy the contents of one folder and save the data to another. The command is responsible for copying robocopy:

Robocopy C:/data D:/backup /e pause

By running such a batch file for execution, you will copy all the contents data folders to the backup folder, including subdirectories, empty and with files. By the way, the robocopy command has many parameters that allow you to configure copy parameters very flexibly.

Run bat files as administrator and on a schedule, hidden bat launch

Now you know how to create batch files and have some general idea about the CMD interpreter language. Those were the basics, now it's time to get acquainted with some useful features working with bat files. It is known that programs require administrator rights to perform some actions. Batniks may also need them. The most obvious way to run the script as administrator is to click on it right click mouse and select in context menu the corresponding option.

In addition, you can make sure that a specific batch file will always be launched with elevated privileges. To do this, you need to create a script like this regular shortcut, open its properties, click the “Advanced” button and check the “Run as administrator” box in the window that opens. This method is also good because it allows you to select any icon for the shortcut, while a file with a BAT or CMD extension will always have a nondescript appearance.

Scripts, like all applications, can be launched on a schedule. Team timeout/t is not entirely appropriate here; for delayed launch, it is best to use the built-in “Task Scheduler” of Windows. Everything is simple here. Open with the command taskschd.msc Scheduler, decide on the trigger, select the action “Run program” and specify the path to the bat file. That's all, the script will be launched at the scheduled time.

And finally one more interesting point. When you run a bat file, a command line window appears on the screen, even if only for a fraction of a second. Is it possible to make the script run in hidden mode? It is possible, and in several ways. The simplest one is as follows. Create a shortcut for the bat file, open its properties and select “Collapsed to icon” from the “Window” menu. After this, the only visible sign of the script running will be the appearance of the CMD icon on the taskbar, but no windows will open.

If you want to completely hide the execution of the script, you can use a “crutch” - the VBS script, which will launch your batch file in hidden mode. The script text is below, save it to a file hidden.vbs, having previously replaced the path in the second line of code D:/script.bat path to your body file.

Set WshShell = CreateObject("WScript.Shell") WshShell.Run chr(34) & "D:\script.bat" & Chr(34), 0 Set WshShell = Nothing

There are also other options, for example, using the utility Hidden Start, which allows you to run executable and batch files in hidden mode, including without an invitation.

And that's all for now. Information regarding creation BAT scripts can be easily found on the Internet. It's also a good idea to check out William Stanek's "Command Line" tutorial. Microsoft Windows" Despite the fact that more than ten years have passed since the publication of the book, the information contained in it is still relevant.

In this article, we will look at two ways to create a bat file: using Explorer and using Notepad. This will be enough to create new bat files, but first let’s decide what they are for. To put it simply, the bat file is needed to write down a set of commands once Windows command line, and then execute them at any time without typing each time. In general, an ideal option for lazy and/or system administrators. =)

I'll get straight to the point:

Method one. We create bat file V " Conductor»

Let me make a reservation right away that this method requires that there be Enabled display of file extensions in Explorer. This is convenient in many cases and I don't understand why this feature is disabled by default in Windows.

We change its extension(what comes after last point) on .bat:

After we press Enter, Windows will ask “After changing the extension, this file may no longer be accessible. Make the change?" Well, of course “Yes”! This is exactly what we are trying to achieve: change the .txt extension to .bat:

Voila! We received a “batch file”, i.e. an executable file in which you can enter commands that will be executed when it starts:

Method two. We create bat file V " Notepad»

To create a bat file using " Notepad", need to open Notepad(or any text file in Notepad) and use the menu " File", option "":

A file saving window will open. It is important to take into account 2 things:

  1. « File type» must be displayed on All files (*.*)
  2. « File name" must have the extension .bat

We look where we save (to find it later) and press the button “ Save»:

Total:

Any of these methods makes sense if you have administrator rights. But the first one requires additional settings(which I still recommend changing and applying).

Batch or batch files are ordinary text files containing sets of interpreter commands and having bat extension or cmd (cmd only works in NT family OSes). You can edit such files using notepad or any other text editor.

Open notepad and type the following two lines:

@echo This batch file
@pause

This batch file
Press any key to continue...

After pressing any key, the window will close, because bat file is completed.
Please note that the dog symbol before each command in the bat file indicates that the command itself does not need to be displayed on the screen, but only the result of its operation should be displayed. To experiment, remove the dog character from the beginning of each line, save and run the resulting bat file.

Commands used in bat files

The list of commands that can be used in bat files can be viewed by entering the command in the command line (Start - Run - cmd for Windows NT family or Start - Run - command for the 9x line)

Result of help - list available commands with brief explanations for them. To get more detailed information For the command you are interested in, enter help command_name in the command line. For example, to get detailed information using the AT command keys, run the following command:

As a result, a list of keys for running the AT command from a bat file will be displayed on the screen.
If the bat file is executed under Windows control(not in pure DOS), then you can launch any applications or open files from it. For example, you need to automatically open the log file of the bat file when it completes its work. To do this, just include the following command in the bat file as the last line:

start filename.txt

The result of executing this command will be the opening of the file file_name.txt, and the bat file itself will complete its work. This method is good if the log file Not large size, otherwise Notepad will refuse to open it, suggesting you use WordPad. But this problem can also be solved, as will be shown in further examples.

How to automate the launch of bat files

Very often it is necessary to automate the launch of bat files to execute them routine operations. To run bat files on a schedule, the Scheduler included in the standard Windows package is most suitable. With this help, you can very flexibly configure the launch of a batch file in certain days or hours, at a certain interval. You can create multiple schedules, etc.

For local launch batch files, you can use solutions from third companies, fortunately paid and free alternatives There are a lot of things for the standard Planner.

Batch files can also be used as login scripts in domains. When used in this way, they will be executed every time the user logs into the network, regardless of his desire. With their help, you can automate the collection of information about machines or software installed on user computers, force change Windows settings, install unnoticed by the user software and automate the solution of other tasks, the manual execution of which would take a lot of time.

How to create a file with an arbitrary name from a bat file

A redirection symbol is used to create a file during batch file execution. It looks like this:
>
Those. to create a file you need to redirect the stream from the screen to the file. This can be done using the following command:

@echo Start file>C:\1.txt

After executing this command, a text file with line Start file.
When creating a file, you can use system variables or parts of them in its name. For example, you can create a report file about the operation of a bat file with a name equal to the date the bat file was launched. To do this, you can use the following lines in the bat file.

set datetemp=%date:~-10%
@echo .>%SYSTEMDRIVE%\%DATETEMP%.txt

These two lines work like this. First, we create a datetemp variable in memory, to which we assign 10 characters from right to left from the DATE system variable. Thus, now the temporary variable datetemp contains only the current date. With the next line, we redirect the output of the dot symbol to a file, the name of which is taken from the datetemp variable, and the txt extension is specified explicitly. The file will be created at system disk the computer where the bat file is running.

When an administrator collects information about computers on the network, it will be more convenient to add the computer name to the file name. This can be easily done using the following command:

@echo .>C:\FolderName\%COMPUTERNAME%.txt

This command, while executing a batch file, will create a text file on drive C with the name of the computer on which the batch file is running.
To create a file with a certain name You can use any system variables, or create your own based on system variables and/or other data.

How to create a folder from a bat file

To create a folder, use the MKDIR command or its abbreviated equivalent MD. To create a folder from a bat file you need to use the following command:

After executing this command, a FolderName folder will be created in the folder from which the bat file was launched. To create a file in a location other than where you started the bat file, for example in the root of drive D, use an explicit indication of the location of the new folder. The command will look like this:

MD D:\FolderName

When creating folders, you can use system variables. For example, you can create a folder in the root of drive D with the name of the current user. To do this, you will need the %USERNAME% variable, and the command will look like this:

MD D:\%USERNAME%

You can further complicate the command and create a folder with the name of the current user on the system drive of his computer. The command for this would look like this:

MD %SYSTEMDRIVE%\%USERNAME%

When creating folders or files, you can use any system variables or parts thereof. The following example demonstrates the creation of a folder on the system drive of the user's computer with a name equal to the current date.

set datetemp=%date:~-10%
MD %SYSTEMDRIVE%\%datetemp%

This design works as follows.
The first command creates a datetemp variable in memory, which will be destroyed when the bat file finishes running. Until the bat file has finished its work, it is possible to operate with the value of this variable. The datetemp variable is assigned 10 characters from right to left of the DATE system variable, i.e. from current date. The DATE variable has the format Day DD.MM.YYYY. The first characters on the left are the name of the day of the week, so we discard them and assign only the current date to the temporary variable datetemp.
This does not limit the list of possibilities when creating folders. You can manipulate variables the way you want, creating folders with unique, easy-to-read names. You can get a list of all variables using the SET command.

How to redirect the result of command execution to a file

Often, when executing a complex bat file in automatic mode It can be difficult to verify the results of its work for many reasons. Therefore, it is easier to record the results of your work bat commands ch file to a text file (log file). and then analyze the correct operation of the bat file using this log.
Redirecting the result of bat file commands to a log file is quite simple. The following will show how this can be done.
Create a bat file with the following content (copy these lines into Notepad and save the file with the bat extension):

@echo off
echo Start %time%
echo Create test.txt
echo test>C:\test.txt
echo Copy Test.txt to Old_test.txt
copy C:\test.txt C:\Old_test.txt
echo Stop %time%

The first line disables the output of the commands themselves. Thus, only the results of their execution will be written to the log file.
The second line writes to the log file the start time of the batch file.
The third line writes to the log file an explanation that the following command will create a test.txt file
The command from the fourth line creates a file test.txt from the root of drive C. The file is created for example. This command writes the word test to the file C:\test.txt
The fifth line prints to the log file an explanation that the following command copies a file from one location to another.
The command in the sixth line copies the created file C:\test.txt to the file C:\Old_test.txt, i.e. a copy of the file is created under a new name.
The last, seventh line contains a command to display the completion time of the batch file. Together with the recording of the start time of the batch file in the log file, these two time values ​​make it possible to estimate the running time of the batch file.

Save this batch file with a name like 1.bat
Let's assume that we would like to store a report on the operation of a batch file in separate folder and write a report every day with a new file name, so that you can access the logs for previous days on any day. Moreover, I would like to have the name of the log file in the form of the date of operation of the batch file. To implement all this, let’s create a folder on drive C (for example) named LOG, i.e. full path it will look like C:\LOG. We will run the created batch file 1.bat with the following command:

1.bat>C:\LOG\%date~-10%.txt

If the batch file will be launched from the Scheduler, then you need to specify the full path to the bat file. Remember that if there are spaces in the path, you must use either quotes or 8.3 format. That is, if the path to the bat file is C:\Program Files\1.bat, for example, then in the Scheduler command line to run the bat file you need to specify one of the following lines:

"C:\Program Files\1.bat">C:\LOG\%date~-10%.txt
C:\Progra~1\1.bat>C:\LOG\%date~-10%.txt

After running the 1.bat file, a file will be created in the C:\LOG folder with a name equal to the date the bat file was launched, for example, 01/13/2004.txt This will be a report on the operation of the 1.bat batch file
Running the bat file, an example of which is shown in the first listing at the top of the page, using the above command, will create a log file with the following content:

Start 19:03:27.20
Create test.txt
Copy Test.txt to Old_test.txt
Files copied: 1.
Stop 19:03:27.21

Thus, to redirect the results of a bat file to a log file, you need to use the redirection symbol > The syntax is as follows:

Path\FileName.bat>Path\LogFileName.txt

The log file extension can be anything. If desired, a report on the execution of a batch job can even be formatted in the form html pages(the corresponding tags can be output to a log file in the same way as comments were output in example 1.bat) and copy it to the corporate server.

How to automatically respond to a confirmation request

Some commands require confirmation of a potentially dangerous action when executed. For example, commands such as format or del will first ask for confirmation before further execution. If one of these commands is executed in a batch file, then the confirmation prompt will stop the batch file from executing and it will wait for the user to select one of the given options. Moreover, if the result of executing a batch file is redirected to a log file, then the user will not see a confirmation request and the batch file will appear frozen.

To correct such troubles, you can redirect the desired response to the command. Those. execute reverse action to redirect the output of the command to a file.
Let's look at an example of what a request to confirm a potentially dangerous action looks like. Let's create, for example, a Folder folder on drive C. Let's create or copy any two files into it. Next, open the command line and run the following command:

This command should remove all files from the specified folder. But first you will be prompted to confirm the following content:

C:\Folder\*, Continue ?

Execution of the command will stop until either the Y key or the N key is pressed. When executing a batch file in automatic mode, its execution will stop.
To avoid this we use redirection. Redirection is carried out using the symbol
The vertical line indicates that instead of displaying the symbol on the screen, it should be “given” to the command following the symbol. Let's check the redirection. Run the following command at the command line:

echo Y|del C:\Folder

The screen will display a request to confirm the deletion of all files in the Folder folder, but with a positive answer (Y). All files from folders will be deleted.
Be careful with this command.

How to disable commands being displayed when executing a batch file

When executing a batch file, in addition to the results of the command, the commands themselves are also displayed. You can use the @ symbol to suppress command output.
To avoid printing one command on the screen, you can put an @ sign at the beginning of the command.

This command will display the echo Testing command, and next line- the result of her work, the word Testing.

This command will only display the result of the command, i.e. the word Testing. The command itself will not be output.
If you do not need to display commands on the screen throughout the execution of the entire file, then it is easier to write the following command as the first line in the batch file:

This command will disable command output to the screen for the duration of the entire batch file. To prevent the command itself from being printed, it begins with the @ symbol.

How to run another from one bat file

Sometimes, while executing a batch file, it becomes necessary to run another batch file. Moreover, in some cases, the execution of the main batch file must be suspended while the auxiliary file is executed, and in others, the auxiliary file must run in parallel with the main one.
For example, let's create two bat files. One named 1.bat and containing just one command

The second one is named 2.bat and also contains one command

Now let's run the 1.bat file. A window will open in which you will be asked to press any key to continue, after pressing which the window will close. Thus, calling one batch file to another using the call command stops execution of the batch file until the batch file called by the call command completes execution.

In another case, you need to launch either an application or another batch file from a bat file without interrupting the execution of the main batch file. This often needs to be done, for example, by forcibly opening the log of a batch file scheduled for the night, so that in the morning the user can check the correctness of its execution. To do this, use the start command. Let's correct the line in file 1.bat to

and run the 1.bat file. Now a window has opened in which you need to press any button to continue, and the window of the main batch file (1.bat) has closed.
Thus, to call another from one batch file, without stopping the first batch file, you need to use the start command.
The start and call commands discussed above can be used not only to launch other batch files, but also to launch any applications or open files.
For example, the start log.txt command in the body of a batch file will open the log.txt file in Notepad without stopping the batch file.

How to send a message from a bat file

When a batch file is executed on one of the machines on the network, it is convenient to inform the administrator that its execution has finished using a message sent to the administrator's machine. You can do this by including the command in the batch file

net send name Message text

Where name is the name of the machine or user to whom the message is addressed, and Message text is the text of the message. After running this command, a message will be sent to user name.
Please note that when using Cyrillic in the text of a message, the text must be typed in MS-DOS encoding (866 code page). Otherwise, the message will arrive in the form of unreadable characters. You can type text in DOS encoding using any text editor that supports this encoding. This could be, for example, FAR. Open a batch file for editing in FAR (F4) and press the F8 button. IN top line editor, the DOS encoding must be indicated, and below, at the hint about shortcut keys, the F8 key should have the inscription Win, indicating that the current encoding is DOS and to switch to the Win encoding you need to press F8.

How to automate file deletion by type

To clear your disk of temporary files, you can use the command

del /f /s /q C:\*.tmp

Where
/f - deletes all files, even if they have the read-only attribute set
/s - deletes files from all subdirectories
/q - disables the request to confirm file deletion
C: is the drive on which files will be found and deleted. You can specify not the entire disk, but a folder, for example, C:\WinNT
*.tmp - type of files that will be deleted

Be careful with the /q switch and the types of files you delete. The command deletes without asking permission and when specified wrong type files can remove unnecessary ones.

How to change a computer's IP address from a batch file

The IP address can be changed using the netsh command.
To correctly change the IP address, you first need to find out the current configuration. This can be done on the command line using the command

netsh interface ip show address

The result of this command is to display the current configuration network interface. We are interested in the name of the interface. Let's say it's called FASTNET.
Let's assume that you need to change the IP address to 192.168.1.42, the network addressing is static, without using DHCP, the gateway is 192.168.1.1, the mask is 255.255.255.0. In this case, the command that must be executed from the batch file will look like this:

netsh interface ip set address name="FASTNET" static 192.168.1.42 255.255.255.0 192.169.1.1 1

After executing this command, the FASTNET interface's IP address will change to 192.168.1.42.
The netsh command provides ample opportunities on management network settings from the command line. To get to know others functionality use help with netsh /?

How to find out the computer name from a bat file

To find out the computer name when executing a bat file (to use this value in the future), use the command

This command returns the name of the computer on which it is running.

How to rename files by mask from a batch file

Sometimes it becomes necessary to rename all the files in a folder using a template from a batch file. This can be done using the following command in the bat file:

for /f "tokens=*" %%a in ("dir /b PATH\*.*") do ren PATH\%%a Prefix%%a

In this line, you need to replace PATH\ with the path to the files that will be renamed, and Prefix with those characters that will be added to the file name when renaming.
Don't put the batch file in the folder where the rename is happening, otherwise it will be renamed too. If there are subfolders in the folder where the files are renamed, then a prefix will also be added to the name of the subfolder, i.e. subfolders will be renamed like files.
If you specify a specific mask for the file types that are subject to renaming, for example, *.txt, and not *.* as in the example, then only files of the specified types will be renamed. Other files and folders will not be renamed.

Second option:
set thePATH=C:\test
for %%I in (*.txt) do ren "%thePATH%\%%~nxI" "%%~nI.dat"
How to use the percentage symbol in a batch file

To use the percent symbol (%) in a batch file, you must write it twice. For example
echo 50%%
This command in the bat file will display 50%. If you use the command echo 50%, then only the number 50 will be displayed on the screen.
Take this feature into account when using the % symbol when writing batch files.

How to export the registry from a batch file

regedit.exe -ea C:\environment.reg "HKEY_CURRENT_USER\Environment"

This command, when executing a batch file, will dump the HKEY_CURRENT_USER\Environment branch into the file C:\environment.reg When you need to restore the parameter values ​​in HKEY_CURRENT_USER\Environment, it will be enough to run the environment.reg file. This command can be used to make a daily backup of software and system settings that are stored in the registry.
Do not forget that if there is a space in the path where the output file should be saved or in the name of the registry hive, they must be enclosed in quotes.

How to import registry variable values ​​from a batch file

If there is a need to import previously saved or new variable values ​​into the registry from a batch file, this can be done using the command

regedit.exe -s C:\environment.reg

This command imports data from the environment.reg file into the registry without asking for confirmation by using the -s switch.

How to bypass date checking from a bat file

Some software checks the current system date upon startup. If the date is greater than what was set by the developer, then the program does not start. For example, the developer believes that a version of the program can work for a month, and then the user will have to install updated version programs. On the one hand, this is a concern for the user, who will have at his disposal the latest version of the program with the shortcomings eliminated in relation to previous versions. On the other hand, the manufacturer forces the user to download new version even if the user is completely satisfied with the version of the program that he has installed. This problem can be easily solved by using the following batch file, which will run the program, wait for it to complete, and return the date to what it was before the program was launched.

set tempdate=%date:~-10%
date 01-01-04
notepad.exe
date %tempdate%

In this example, the current system date is first stored in a variable, then (in the second line) the system date is set to January 1, 2004, and then a program is called that checks the system date. In this example it is Notepad. As long as Notepad is open, the batch file waits without completing or setting the system date back. Once Notepad is closed, the batch file will continue executing and set the system date to the value stored in the tempdate variable, i.e. to the one that was before running the batch file.

Do not forget that if the path to the file that runs the program contains spaces, then it (the path) must be enclosed in quotes. If the path contains Cyrillic, then when writing a batch file you must use a text editor that supports DOS encoding (for example, FAR). Otherwise, when running the batch file, a message will be displayed stating that " specified file is not an internal or external command...".

If the program checks the current system date only when it starts and does not do this again during operation, then the batch file can be modified by adding before the name executable file program operator start, i.e. our example will look like this:

set tempdate=%date:~-10%
date 01-01-04
start notepad.exe
date %tempdate%

In this case, the batch file will change the system date, launch the program and, without waiting for it to complete, return the date to the one that was before the program was launched.

How to wait for the appearance in a bat file specific file

Sometimes it is necessary to perform some action when a certain file appears in a folder. To organize a check for the appearance of a file in a folder, you can use the following batch file

:test
if exist c:\1.txt goto go
sleep 10
goto test
:go
notepad

Such a batch file will check at 10-second intervals for the presence of file 1.txt in the root of the C drive and when file 1.txt appears, the action specified after the go label will be performed, i.e. this example will launch Notepad.
The sleep utility is freely distributed as part of the Resource Kit. You can download it here.
If the 1.txt file is large and is being copied from somewhere, it may happen that the batch file will check for its presence while the file has not yet been copied or is busy with another application. In this case, trying to perform some actions with the 1.txt file will result in an error. To prevent this from happening, the batch file can be modified as follows

:test
if exist c:\1.txt goto go
sleep 10
goto test
:go
rename c:\1.txt 1.txt
if not errorlevel 0 goto go
del c:\1.txt

When the 1.txt file has not been completely copied to drive C, or is occupied by another application, an attempt to rename it will cause an error and the cycle will be repeated until the file is copied completely or is freed. After the rename c:\1.txt 1.txt command is executed without an error (i.e. the file is free), you can perform any actions with it. In the last example it is removing it.

How to add comments to a bat file

When writing a large batch file, it is very useful to add comments to its main blocks. This will make it easy to understand what these blocks do over time.