Ready-made batch files. Bat files, examples. Create a new text document

To open the command line in the right place (in the folder with files, for example), you need to call the context menu (RMB) while holding down the Shift key:

About how to work with the command line you. Let's go directly to the commands.

A list of all console commands with a description can be obtained by typing help in the console
Help for any command can be obtained using the /?
For example: DIR /? will display help for all DIR command options

Deleting temporary files before shutting down the computer

I think that everyone at least or faced them personally. The Bat file will help you properly shut down your computer by deleting temporary files, in the folder with which the virus usually downloads.

The next time the device boots (at an early stage), the virus makes entries in the registry, disrupting the normal operation of the system. And when the desktop loads, the situation is already more difficult to fix.

Of course, not all viruses work according to this scheme, but nevertheless, clearing temporary files and the system cache before shutting it down significantly reduces such risks.

start /wait "" "C:\Program Files\CCleaner\CCleaner64.exe" /auto start /wait "" "C:\WINDOWS\System32\shutdown.exe" /s /t 10

CCleaner is not available by default on Windows. It needs to be installed separately. You can download the installer from the developer's website.

The CCleaner program is launched first and removes all temporary files on the computer. Then the computer shutdown program is launched with a delay of 15 seconds to avoid possible conflicts with the operation of CCleaner.

It is also necessary to copy this example into it. Bring the shortcut to the bat file to the desktop, assign it a beautiful icon and turn off the computer using this shortcut button.

Get list of files in a folder using bat file

Periodically I use bat-files to get lists of files in folders. A common situation: at work, clients send an archive with photos from the photographer. The photographs are titled according to the article numbers of the goods.

There is no textual information accompanying the photo. It is necessary to make a list based on the photos sent and import it into the product catalog on the site. Each item has multiple photos. They are named like this:

  1. Photo of goods with article number А1234 (2).jpg
  2. Photo of goods with article B1234 (2).jpg

First, I get a list of all the files in a folder with the following command:

dir *.jpg /B /L > filelist.txt

The *.jpg command will allow only JPG files to be considered when compiling the list. The /B switch will allow you to get a list containing only the names of the files in the folder. The /L switch will output all names in lower case. The >filelist.txt command will create a text file named filelist and write the output there.

The next step is to get rid of duplicates so that only one entry for each product remains in the list:

filelist.txt | findstr /I /V "(2)" > temp.txt

The findstr command will search in the previously retrieved file. The /I switch allows you to search for records in a case-insensitive way, and the /V switch writes lines that do not contain the desired match. The quotes indicate the string to be matched. And the last command > temp.txt will write to the temp file all results that do not contain "(2)" in the name. As a result I will get:

  1. Photo of goods with the article A1234.jpg
  2. Photo of goods with the article B1234.jpg

If you need to perform the reverse operation - output only matches to the temp.txt file, then you will not find the required one in the list of commands ( findstr /? ). There is only reverse filter by exact match - /X .

For this task, you can use the /N command to display line numbers that have matches (numbers are displayed along with the line):

filelist.txt | findstr /I /N "(2)" > temp.txt

The main thing when working with text information (text files) is to remember one thing:

If for text operations you use as a source a file that was not created via the command line, it must be in an encoding that is understood by the command line. For example, CP1251 (ANSI).

Otherwise, you risk getting something like this:

Copy directory tree without files

When I start making new projects, it becomes necessary to get a directory tree similar to the old project one, with the difference that it should not contain files. For a new project, it is easier to add 3-5 files to the necessary empty folders than to copy an existing project and then delete unnecessary ones from there.

Get directory tree without files you can use the following command:

xcopy folder_1 folder_2 /T /E

The xcopy command takes the directory tree at folder_1 as a base and creates a copy of it in folder_2 . The /T switch allows you to copy directories without copying the files contained in them. The /E switch specifies that all directories must be copied, incl. empty.

Optimally, to get a directory tree, you need to open a command line in the parent folder of the donor directory and in the same folder create a directory in which the copied tree will be placed. In this case, the command will only need to specify the names of the donor folder and the destination folder (as in the example above).

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

Automation made easy

How to create a bat file? To do this, follow these steps:

  1. In any text editor, such as Notepad or WordPad, create a 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 to be displayed] and pause.
  3. Save the text in an electronic document with the .bat extension (for example, test.bat).
  4. To run it, double-click on the batch file you just created.
  5. To edit it, you need to right-click on it and select "Edit" from the context menu.

The raw file will look something like this:

title This is your first bat file script!

echo Welcome to the batch script!

More details about the bat-file commands and their use will be discussed below.

Step 1: Create a Software Script

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

Create a new text document

A batch file makes it easy to perform repetitive tasks on a computer using the Windows Command Prompt. 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 text editor. You can copy and paste the code example above into a text entry.

Preservation

The above script prints the text "Welcome to the Batch Script!" on the screen. An electronic document must be recorded by selecting the menu item of the text editor "File", "Save as", and then specifying the desired name of the bat-file. It should end with a .bat extension (for example, welcome.bat) and click OK. For the correct display of the Cyrillic alphabet, in some cases it is necessary to make sure that the encoding is chosen correctly. For example, when using the console of a Russified Windows NT system, the document must be saved to the CP866. Now you should double click on the shortcut of the bat file to activate it.

But the screen will display:

"Welcome to the batch script! Press any key to continue..."

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

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

Do not think that this is all that batch scripts are capable of. 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: Getting to Know Some Commands

If a PC user is familiar with how to execute DOS console commands, then he will be a wizard for creating program scripts, because it is 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 define some logic (for example, simple loops, conditional statements, 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 the working code. If the batch file has any problems, then this command will allow you to quickly isolate the problems. Adding off makes it possible to quickly complete code execution, avoiding displaying unnecessary information on the screen.

2. Title provides the same functionality as the tag in HTML, i.e. creates a title 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 the number %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 color f9 command sets white letters on a blue background. A command without a parameter restores the default settings.</p><p>6. Echo is used to output information, as well as enable (echo on) or disable (echo off) such an output. For example, the echo command. outputs a newline without a dot, while 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 bat-file commands. This makes it possible to read the executed lines before continuing the program. The message “Press any key to continue...” 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 option, it allows you to perform simple arithmetic operations, also assigning their result to a variable. When operating on strings, there must be no spaces before or after the equals sign. For example, the set command displays a list of environment variables, set HOME displays the values ​​of arguments beginning with “HOME”, and set /p input=input integer: prompts for an integer and assigns it to the corresponding variable.</p><p>10. Start "" [website] will launch the specified website in the default web browser.</p><p>11. If is used to test a certain condition. If it is true, then the command following it is executed. There are 3 types of conditions:</p><ul><li>ERRORLEVEL number - checks the exit code of the last executed instruction to match or exceed the specified number. In this case, 0 indicates the successful completion of the task, and any other number, usually positive, reports an error. For example, you can use nested commands to determine the exact exit code: if errorlevel 3 if not errorlevel 4 echo error #3 occurred.</li><li>Line1 == line2 - check if two strings match. For example, if "%1"= ="" goto ERROR does not have an external parameter, it will pass control to the label ERROR.</li><li>EXIST name - check for the existence of a file with the specified name. For example, if not exist A:\program.exe COPY C:\PROJECTS\program.exe A: copies the program program.exe to drive A if it does not exist.</li> </ul><p>12. Else must be on the same line as the If command. Indicates that the next statement should be executed if the expression evaluates to false.</p><p><img src='https://i0.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 with each member of the list. It 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 disks 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 path to C:\ WAT.</li> </ul><p>14. A colon (:) in front of a word forms a link from it, which allows you to skip part of the program code or go back. Used with the Call and Goto commands, indicating from which point the execution of the bat file should continue, for example, if a certain condition is met:</p><p>15. Variables:</p><ul><li>%%a stands for each file in the folder;</li><li>%CD% - current directory;</li><li>%DATE% - system date, the format of which depends on localization;</li><li>%TIME% - system time as 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>To extract the part of the string that is contained in the variable, given its position and length, you can do this:</p><p>%[variable]:~[start],[length]%. For example, to display a date in the format DD/MM/YYYY as YYYY-MM-DD, you can do 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 action of the command to a specific directory. When using a batch file, just run it in any desired directory.</p><p>17. %digit - accepts the values ​​of the parameters passed by the user to the bat-file. May be separated by spaces, commas, or colons. "Digit" is a number between 0 and 9. For example, %0 takes the value of the current command. %1 matches the first parameter, and so on.</p><p>18. Shift is a command used to shift input parameters by one position. Used when external arguments are passed to a batch file. For example, the following .bat file copies the files specified as options on the command line to drive D:</p><p>if not (%1)==() goto next</p><p>In addition, the following manipulations can be performed with 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 path only;</li><li>%~n - select only the file name from the parameter;</li><li>%~x - leave only the extension;</li><li>%~s - convert path to representation with short names;</li><li>%~a - extract file attributes;</li><li>%~t - display creation date and time;</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 on failure.</li> </ul><p><img src='https://i1.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 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 dot (.).</li> </ul><p>For example, the command dir *.txt lists txt files, and dir ???.txt lists text documents whose name does not exceed 3 letters.</p><h2>Functions</h2><p>Like subroutines, they are emulated using call, setlocal, endlocal, and labels. The following example demonstrates the ability to define a variable that stores the result in a call string:</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>Computing</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 similar to the C programming language. Arithmetic operators include: *, /, %, +, -. In a bat file, % (the remainder of an integer division) must be entered as "%%".</p><p>The binary number operators interpret the number as a 32-bit sequence. These are: ~ (bitwise NOT or complement), & (AND), | (OR), ^ (XOR),<< (сдвиг влево), >> (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 performed 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. *=, %=, /=, &=, |=, ^=, >>=,<<=. Приоритет операторов следующий:</p><p>(); %+-*/; >>, <<; &; ^; |; =, %=, *=, /=, +=, -=, &=, ^=, |=, <<=, >>=; ,</p><p>Literals can be entered as decimal, hexadecimal (with leading 0x), and octal (with leading zero). For example, set /a n1=0xffff sets n1 to 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 subroutine.</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 by sending data packets to it in order to estimate its distance and wait (response) time. Also used to set a pause. For example, ping 127.0.01 -n 6 pauses code execution for 5 seconds.</li> </ul><p>The bat file command library is huge. Luckily, there are plenty of 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 activities much easier. What if you want to instantly open all your favorite news sites? Since scripts use console commands, it is possible to create a script that opens each 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, right-click on an empty space in a 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 start “” commands that open multiple 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>Once saved, double-click on the script to run it. Web pages will start loading instantly. If you wish, you can place this file on your desktop. This will give you instant access to all your favorite sites.</p><h2>Organizer</h2><p>If you upload several files a day, then soon hundreds of them will accumulate in the Downloads folder. You can create a script that will sort them by type. It is enough to place the .bat file with the program in the unorganized data folder and double-click to run:</p><p>rem each file in a 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 if there is a folder for each extension, and if it doesn't exist, 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, the 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 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, then the program will simply move files with this extension there.</p><p>This is a simple demonstration of what batch scripts are capable of. When a simple task needs to be done over and over again, whether it's organizing files, opening multiple web pages, bulk renaming, or making copies of important documents, a batch script can get the tedious job done in a couple of clicks.</p> <i> </i> <p>The use of a graphical interface in operating systems today seems to be something taken for granted and completely natural, but it was not always so. The first MS DOS operating system developed by Microsoft did not have a GUI, and control was performed by entering text commands. Nearly 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 available from the GUI. On the other hand, launching the console every time, entering commands one after the other into it - all this greatly slows down the work. However, you can significantly simplify the task by creating a batch 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, such as deleting temporary files on a schedule or launching programs.</p> <h2><span>How to create a .bat file</span></h2> <p>So, how to create a bat file in Windows 7/10? Very simple. To do this, you need any text editor and knowledge of the basics of the command line. You can use Notepad, and even better Notepad ++, since the latter has syntax highlighting. Create a new file in the editor, select "Save As" from the "File" menu, give the future script a name, and select "Batch file (*bat; *cmd; *nt)" from the "File type" drop-down list.</p> <p><img src='https://i0.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. Line breaks cannot be used in batch files, the bat-file encoding must be set to UTF-8, if Cyrillic is used in the script body, the encoding must be changed by inserting the chcp 1251 command in the proper place.</p> <p>Instead of the BAT extension, you can use CMD, the result of running 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 thing, namely the syntax of the CMD interpreter language. It is clear that an empty batch file will not work, it will not even start when you double-click on it. For the script to work, it must contain at least one command. For an illustrative example, let's see how to write a bat file to run programs. Let's say that when you get started, you launch three programs each time - Chrome, Firefox, and VLC. Let's simplify the task by creating a script that will run 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://i0.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 the executable file of the desired program, and the command <b>timeout /t</b> sets the interval between runs. Pay attention to the location of the quotes - they take paths that contain spaces. Also, if there are Cyrillic characters in the path, you should insert the 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://i1.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 open in succession, this is normal, after the commands are executed, all of them will automatically close, however, you can make sure that only the first window opens. To do this, the application startup code should be changed as follows:</p><p>Start /b "" "path"</p><p><img src='https://i1.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 himself can decide whether to execute all other commands or not. For this there is a command <b>pause</b>. Try replacing timeout with it and see what happens.</p><p>Start /b "" "path" pause</p><p><img src='https://i2.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-7.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>Consider 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 the other. For this purpose, 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 the batch 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://i0.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-9.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <p>We 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 it off, and with the key <b>/r</b> instead of <b>/s</b> restarts the computer without the traditional one-minute delay. If you do not want to stand on ceremony with requests and pauses, you can leave only the fifth team.</p> <p>If instead of Russian text when you run the command you see cracks, try converting the script file to ANSI.</p> <p>What else can you do with scripts? Lots of things like delete, copy or move 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>And it's possible like this:</p><p>Forfiles /p "D:/data" /s /m *.* /c "cmd /c Del @path"</p><p><img src='https://i2.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 command, the second command deletes files recursively, that is, all files in the data folder will be deleted plus those in subdirectories.</p> <p>Here is another useful example. Let's write a script that will create a backup copy of the contents of one folder and save the data to another. Responsible for copying <b>robocopy</b>:</p><p>Robocopy C:/data D:/backup /e pause</p><p><img src='https://i0.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 the entire contents of the data folder to the backup folder, including nested directories, empty and with files. By the way, the robocopy command has many options that allow you to customize the copy settings very flexibly.</p> <p><img src='https://i1.wp.com/viarum.ru/wp-content/uploads/kak-sozdat-bat-fail-13.jpg' align="center" width="100%" loading=lazy loading=lazy></p> <h2><span>Running bat files as administrator and scheduled, hidden bat launch</span></h2> <p>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 of working with bat files. Programs are known to require administrative 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 the appropriate option from the context menu.</p> <p><img src='https://i2.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 run 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 choose any icon for the shortcut, while a file with a BAT or CMD extension will always have a nondescript look.</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 scheduled to run. Team <b>timeout /t</b> is not entirely appropriate here, for a delayed start it is best to use the built-in "Task Scheduler" of Windows. Everything is simple here. We open with a team <b>taskschd.msc</b> The scheduler, we determine the trigger, select the action "Run the program" and specify the path to the bat-file. That's it, the script will run at the appropriate time.</p> <p><img src='https://i0.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://i1.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://i0.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 stealth mode? It is possible, and in several ways. The simplest one is as follows. We create a shortcut to the bat file, open its properties and select “Minimized to icon” in the “Window” menu. After that, 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://i0.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 the "crutch" - the VBS script, which will run your batch file in hidden mode. The text of the script is given below, save it to a file <b>hidden.vbs</b>, after replacing the path in the second line of code <i>D:/script.bat</i> way to your batch 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, such as using the utility <b>Hidden Start</b>, which allows you to run executable and batch files in stealth mode, including without an invitation.</p> <p>And that's all for now. Information about creating BAT scripts can be easily found on the Internet. It's also a good idea to check out William Stanek's "Microsoft Windows Command Prompt" tutorial. 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> <p>As experience has shown batch files, ie. <b>batch files</b> are very popular among system administrators who use them for their automation purposes. And today we continue to study these very bat files, we will not consider the basics, but we will move on to more advanced things.</p> <p>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 for almost everyone and everyone already wants to learn something more complex, with which you can further simplify the automation of some processes.</p> <i> </i><h2>Example 1 - deleting old archives</h2> <p>When archiving something, many are interested in the question " <i><b>How to delete old archives as unnecessary using a batch file?</b> </i>". For example, they are all in the same folder and you need to delete all archives that are older than 14 days. After I read the manuals, climbed on the Internet, I can offer the following method.</p> <p>You can make it so that only a certain number of archives will be stored in the folder with archives, respectively the latest ones ( <i>those. just in our case for the last 2 weeks</i>).</p> <p>This is done with two commands. The first is DIR, i.e. we simply read all the files in one folder, and write their name to a text file.</p> <p><b>dir D:\archiv\*.rar /a:-D/b/o:-D > list_of_files.txt</b></p> <ul><li><b>dir D:\archive\*.rar</b>– this means that we are reading all rar archives in the D:\arhiv\ folder;</li> <li><b>/a:-D</b>- this means that all files with the specified attributes will be displayed, the -D switch means that we need only files, not directories, the prefix “-” just means negation, i.e. not directories, if we just wrote D, then it would also read directories;</li> <li><b>/b</b>- this is the output of only filenames;</li> <li><b>/o:-D</b>- this is sorting, the -D key means that sorting will be performed by date, but first older ones, to fix this, we already know that the “-” prefix will help us;</li> <li><b>> </b>- means that the output will be redirected to the list_of_files.txt file, you can name it differently.</li> </ul><p>So we counted all our archives and wrote them to 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 with the command <b>FOR</b>, 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.</p> <ul><li><b>for</b>- the command itself for the bulkhead;</li> <li><b>/F "skip=13"</b> is a key with a parameter that means that the first 13 files should not be processed, i.e. we skip them. Why 13 and not 14 yes because 14 archive ( <i>those. today, which should be created when executing this batch file</i>) has not yet been created, so 13;</li> <li><b>%%i</b>– a variable that stores the name of the current file;</li> <li><b>In(list_of_files.txt)</b>- means that iterate over all lines in this file;</li> <li><b>do (del /Q "%%i")</b>- says what needs to be done with each, in our case we simply delete these files using the del / Q key / Q, so that we are not asked for confirmation before deleting. I advise you to replace del / Q with echo for tests, i.e. just display those files.</li> </ul><p>In total, we got this batch file:</p> <p><b>dir D:\archiv\*.rar /a:-D/b/o:-D > list_of_files.txt</b></p> <p><b>for /F "skip=13" %%i in (list_of_files.txt) do (del /Q "%%i")</b></p> <p>Accordingly, after these lines, you can write the archiving code itself, and as a result, we will have only 14 archives stored in our folder, of course, the latest ones.</p> <h2>Example 2 - using variables</h2> <p>You can even use variables in batch files, just like in a real programming language. Consider the simplest example of using variables, for example, we want to multiply by 2 the number that we enter into the field when starting the batch file.</p> <p><b>@echo off</b></p> <p><b>SET /a c=%a%*%b%</b></p> <p><b>echo %c%</b></p> <p>As you understand, variables are set using the SET command. In order to use the variable in the future, we substitute the percent sign (%) on both sides of the variable so that the command line understands that this is a variable.</p> <ul><li><b>@echo off</b>- so that our commands are not displayed on the screen;</li> <li><b>SET a=2</b>- it's just set the value of the variable "a";</li> <li><b>SET /p b=[enter second number to multiply]</b>- we set the variable “b” to the value that we will enter in the field, in order for the batch file to understand that we want to enter the value of the variable ourselves, the /p key is used;</li> <li><b>SET /a c=%a%*%b%</b>- set the variable "c" the result of our expression ( <i>in our example it is multiplication</i>);</li> <li><b>echo %c%</b>- display the value of the variable "c";</li> <li><b>pause</b>- we just pause the execution of our bat file in order to just see all the results.</li> </ul><p>By the way, in order for you to display Russian letters normally on the command line, save the bat file in DOS-866 encoding.</p> <p>We figured 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 ourselves want, for this we will enter the number of archives to be saved when starting the batch file. It will turn out like this:</p> <p><b>@echo off</b></p> <p><b>dir D:\test\*.rar /a:-D/b/o:-D > list_of_files.txt</b></p> <p><b>for /F "skip=%chislo%" %%i in (list_of_files.txt) do (del /Q "%%i")</b></p> <p>Well, something like this, of course, in practice it may not be needed, but we learned how variables can be used.</p> <p>About variables, I also want to say that there are such system variables as:</p> <p><b>%DATE%</b>- shows the current date.</p> <p><b>%TIME%</b>- shows the current time.</p> <p>For example, run the following code:</p> <p><b>echo %DATE%</b></p> <p><b>echo %time:~0,-3%</b></p> <p>I wrote the %TIME% variable in 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.</p> <p>In fact, there are more system variables, just these may be needed more often than others.</p> <h2>Example 3 - IF Conditional Execution Statement</h2> <p>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 if the file exists or not:</p> <p><b>@echo off</b></p> <p><b>IF EXIST test.txt (</b></p> <p><b>echo File exists</b></p> <p><b>echo No such file</b></p> <p><b>IF EXIST test.txt</b>- this is just the check for the existence of the file.</p> <p>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.</p> <p>Now we slightly modify our example with multiplying by 2 the number we entered, just if we suddenly enter zero, we will display the appropriate message and ask you to enter the number again.</p> <p><b>@echo off</b></p> <p><b>SET /p b=[enter second number to multiply]</b></p> <p><b>SET /a c=%a%*%b%</b></p><p><b>if %c%==0 (echo you entered the number 0, enter another) else echo %c%</b></p> <p><b>if %c%==0 (goto:mark)</b></p> <p>Everything is already familiar here, the only thing is that when comparing the variable “c”, the comparison operator == ( <i>two equals</i>) because just equals (=) is an assignment operator. If you notice, I used the goto statement here, i.e. jump to the desired label. In other words, we put a label and, depending on the result of the condition check, the transition to the desired label will be made.</p> <p>Now I would like to note what many people use in their work, for example, to create an archive, the winrar program and, of course, use it in their batch files, but many ask questions about keys that relate to winrar. You do not 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 already be different. As for winrar keys, the complete and best reference, in my opinion, is, of course, in winrare itself. In order to see the description of winrar keys, open the winrar program, go to the Help menu, then click " <i>Content</i>", and then select the line " <i>Command line mode</i>”, where there will be a description of all the keys, even simple examples are given. Accordingly, if you have an English version of winrar, then the meaning is the same, only everything will be in English.</p> <p>This concludes our second part of studying batch files. Good luck!</p> <script>document.write("<img style='display:none;' src='//counter.yadro.ru/hit;artfast?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> </article> <div class="post-share"> <div>Share with friends or save for yourself:</div> <script src="//yastatic.net/es5-shims/0.0.2/es5-shims.min.js"></script> <script src="//yastatic.net/share2/share.js"></script> <div class="ya-share2" data-services="collections,vkontakte,facebook,odnoklassniki,moimir,gplus,viber,whatsapp,skype,telegram"></div> <br> <div id="post-ratings-14689-loading" class="post-ratings-loading"> <img src="https://unitarmy.ru/wp-content/plugins/wp-postratings/images/loading.gif" width="16" height="16" class="post-ratings-image" / loading=lazy loading=lazy>Loading...</div> </div> <div class='yarpp-related'> <div class="related"> <div class="headline">Recommended related articles</div> <div class="items"> <div class="item"> <div class="item__image"> <picture> <source media="(max-width: 479px)" srcset="/wp-content/themes/unitarmy.ru/cache/945f81849_460x250.png"><img src="/uploads/d9a77407b4fbf77b6b59a6438130fe8f.jpg" width="240" height="240" alt="Analysis of existing targets of network attacks and methods of attacks on angelica web services" / loading=lazy loading=lazy></picture> </div> <div class="item__title"><a href="https://unitarmy.ru/en/kompyuter-zhelezo/analiz-sushchestvuyushchih-celei-setevyh-atak-i-sposobov-atak-na.html">Analysis of existing targets of network attacks and methods of attacks on angelica web services</a></div> </div> <div class="item"> <div class="item__image"> <picture> <source media="(max-width: 479px)" srcset="/wp-content/themes/unitarmy.ru/cache/945f81849_460x250.png"><img src="/uploads/77c5ac81cb9b621f433be5d6d6d2e2aa.jpg" width="240" height="240" alt="The Best Distributions for Penetration Testing Why Hackers Don't Use Windows" / loading=lazy loading=lazy></picture> </div> <div class="item__title"><a href="https://unitarmy.ru/en/windows-8-1/gid-po-kali-linux-testirovanie-na-proniknovenie-luchshie-distributivy-dlya.html">The Best Distributions for Penetration Testing Why Hackers Don't Use Windows</a></div> </div> <div class="item"> <div class="item__image"> <picture> <source media="(max-width: 479px)" srcset="/wp-content/themes/unitarmy.ru/cache/945f81849_460x250.png"><img src="/uploads/f6222d9fccd26586f07af74b83f698f2.jpg" width="240" height="240" alt="How to close windows ports" / loading=lazy loading=lazy></picture> </div> <div class="item__title"><a href="https://unitarmy.ru/en/brauzery/blokirovka-445-port-na-firewall-mezhsetevoi-ekran-kak-zakryt-porty.html">How to close windows ports</a></div> </div> </div> </div> </div> </main> <aside class="sidebar"> <div class="amulets sidebar__section"> <div class="headline">Popular Articles</div> <ul class="amulets__list"> <li class="amulets__list-item"><a href="https://unitarmy.ru/en/noutbuki-i-netbuki/kak-razoslat-vsem-soobshcheniya-vkontakte-uchimsya-peresylat-soobshcheniya-v.html">Learning to send messages on VKontakte</a></li> <li class="amulets__list-item"><a href="https://unitarmy.ru/en/kompyuter-zhelezo/fleshka-postoyanno-prosit-otformatirovat-kompyuter-prosit-otformatirovat-fleshku-chto-delat-vosstan.html">The computer asks to format the flash drive what to do</a></li> <li class="amulets__list-item"><a href="https://unitarmy.ru/en/brauzery/volshebnaya-dyrka-u-kazhdoi-zhenshchiny-imeetsya-bolshoe-kolichestvo-otverstii-kak.html">Every woman has a large number of holes, like</a></li> <li class="amulets__list-item"><a href="https://unitarmy.ru/en/brauzery/o-dorkah-ili-vsem-lyubitelyam-privatnyh-dorok-ispolzuem-maloizvestnye-funkcii-google-chtoby-naiti-so.html">Using Little Known Google Functions to Find Hidden Inurl privat bild php name treasure</a></li> <li class="amulets__list-item"><a href="https://unitarmy.ru/en/google-chrome/zakryt-port-445-v-windows-7-kak-zakryt-uyazvimye-porty-v-windows.html">How to close vulnerable ports in Windows</a></li> </ul> <div class="amulets__all"><a href="https://unitarmy.ru/en/">See all articles</a></div> </div> <div class="sidebar__section sidebar__widget" id="recent-posts-3"> <div class="headline">Latest articles:</div> <ul> <li> <a href="https://unitarmy.ru/en/noutbuki-i-netbuki/instrukciya-po-ispolzovaniyu-jsql-injection-mnogofunkcionalnogo.html">Instructions for using jSQL Injection - a multifunctional tool for finding and exploiting SQL injections in Kali Linux</a></li> <li> <a href="https://unitarmy.ru/en/windows-7/dolgov-profile-powered-by-punbb-shoppinggid-kak-udalit-nadoedlivyi-spam-reestr-i.html">Shoppinggid: how to remove annoying spam?</a></li> <li> <a href="https://unitarmy.ru/en/noutbuki-i-netbuki/kak-napisat-soobshchenie-vsem-druzyam-kak-razoslat-odno.html">How to send one message to all VKontakte friends</a></li> <li> <a href="https://unitarmy.ru/en/mozilla-firefox/kak-stat-hakerom-v-domashnih-usloviyah-kak-priobresti-hakerskie-navyki-znaniya.html">How to acquire hacking skills</a></li> <li> <a href="https://unitarmy.ru/en/windows/podobrat-parol-i-login-k-routeru-zahvatyvaem-router-massovyi-skan-i.html">Capturing the Router: Bulk Scan and SSH Brute Force</a></li> <li> <a href="https://unitarmy.ru/en/windows-8-1/chertovoi-profile-powered-by-punbb-ustanovka-i-rasshireniya-punbb-reestr-i.html">PunBB installation and extensions</a></li> <li> <a href="https://unitarmy.ru/en/brauzery/zameshany-profile-powered-by-punbb-shoppinggid-kak-udalit-nadoedlivyi-spam.html">Shoppinggid: how to remove annoying spam?</a></li> <li> <a href="https://unitarmy.ru/en/windows/gotovye-batniki-bat-faily-primery-sozdanie-novogo-tekstovogo.html">Ready-made batch files. Bat files, examples. Create a new text document</a></li> <li> <a href="https://unitarmy.ru/en/windows-8-1/bezopasnoe-programmirovanie-na-php-krazha-sessii-metody-pohishcheniya.html">Safe PHP Programming</a></li> <li> <a href="https://unitarmy.ru/en/mozilla-firefox/podrobnyi-obzor-prilozheniya-brutfors-vkontakte-brutforser-vkontakte.html">Bruteforcer Vkontakte - VKFucker Download brute program for VKontakte</a></li> </ul> </div> <div class="sidebar__section sidebar__widget" id="text-2"> <div class="textwidget"> </div> </div> </aside> </div> <footer class="footer"><nav class="footer__nav nav"><ul> <li class="menu-item type-post_type object-page "><a href="" itemprop="url">Feedback</a></li> <li class="menu-item type-post_type object-page "><a href="https://unitarmy.ru/en/sitemap.xml" itemprop="url">site `s map</a></li> <li class="menu-item type-post_type object-page "><a href="" itemprop="url">Advertising</a> <li class="menu-item type-post_type object-page "><a href="" itemprop="url">About the site</a></li> </ul></nav><div class="footer__inner"><div class="footer__copyright" style="background:none;"> <div class="footer__copyright-title1"></div> <p>© 2022. All rights reserved <br />Basics of working on a personal computer</p> </div><div class="footer__counters"></div><div class="footer__info"><p></p></div></div></footer> </div> </div> <script type="text/javascript" defer src="https://unitarmy.ru/wp-content/script.js"></script> </body> </html>