• Writing bat files - examples of batch files. What are bat files and why are they needed?

    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.

    Open notepad and type the following two lines:

    @echo This batch file
    @pause

    This batch file
    Press any key to continue...

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

    Commands used in bat files

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

    The result of help is a list of available commands with brief explanations for them. To get more detailed information For the command you are interested in, enter help command_name in the command line. For example, to get detailed help on the AT command switches, run the following command:

    As a result, a list of keys for running the AT command from the bat file will be displayed on the screen.
    If the bat file is executed under Windows control(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:

    start filename.txt

    The result of executing this command will be the opening of the file file_name.txt, and the bat file itself will complete its work. This method is good if the log file 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.

    How to automate launch bat files

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

    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.

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

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

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

    @echo Start file>C:\1.txt

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

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

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

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

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

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

    How to create a folder from a bat file

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

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

    MD D:\FolderName

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

    MD D:\%USERNAME%

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

    MD %SYSTEMDRIVE%\%USERNAME%

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

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

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

    How to redirect the result of command execution to a file

    Often, when executing a complex bat file in automatic mode It can be difficult to verify the results of its work for many reasons. Therefore, it is easier to 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.
    Redirecting the result of bat file commands to a log file is quite simple. The following will show how this can be done.
    Create a bat file with the following content (copy these lines into Notepad and save the file with the bat extension):

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

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

    Save this batch file with a name like 1.bat
    Suppose 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:

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

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

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

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

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

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

    Path\FileName.bat>Path\LogFileName.txt

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

    How to automatically respond to a confirmation request

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

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

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

    C:\Folder\*, Continue ?

    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.
    To avoid this we use redirection. Redirection is carried out using the symbol
    The vertical line indicates that instead of displaying the symbol on the screen, it should be “given” to the command following the symbol. Let's check the redirection. Run the following command on the command line:

    echo Y|del C:\Folder

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

    How to disable commands being displayed when executing a batch file

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

    This command will display the command echo Testing, and on the next line - the result of its operation, the word Testing.

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

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

    How to run another from one bat file

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

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

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

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

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

    How to send a message from a bat file

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

    net send name Message text

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

    How to automate file deletion by type

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

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

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

    Be careful with the /q switch and the types of files you delete. The command deletes without asking permission and, if the wrong file type is specified, it can delete unnecessary files.

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

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

    netsh interface ip show address

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

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

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

    How to find out the computer name from a bat file

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

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

    How to rename files by mask from a batch file

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

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

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

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

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

    How to export the registry from a batch file

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

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

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

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

    regedit.exe -s C:\environment.reg

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

    How to bypass date checking from a bat file

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

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

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

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

    If 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 before the name of the executable file of the program start operator, i.e. our example will look like this:

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

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

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

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

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

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

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

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

    How to add comments to a bat file

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

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

    I'll get straight to the point:

    Method one. We create bat file V " Conductor»

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

    We change its extension(what is after the last dot) on .bat:

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

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

    Method two. We create bat file V " Notepad»

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

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

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

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

    Total:

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

    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), using 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 “ 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 - this 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 in this case we archive everything Word documents, 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 consider basic commands, which 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 don’t 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 this 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, not all the commands that can be used in batch files are there. Good luck in writing BAT files ( body shirts).

    Continuation of the topic in the article -

    People who are familiar with the term batch file know that BAT files can significantly simplify life and save time if you know how to write and use them correctly. In this article, I will talk about how to create BAT files and introduce you to common mistakes that usually occur when writing them.

    Creating a BAT file is very simple. Just open notepad and save blank sheet with the .bat extension, selecting the Save as... option and writing in the File name field something ending in .bat, for example test.bat.
    Specify the file type as in the screenshot below - All files. Save and receive a BAT file.

    You can edit the BAT file in Notepad or any other text editor oriented towards working with code.

    Now let's move directly to practical information. Many people on the Internet are looking for an answer to the question: How to deal with spaces in BAT files? . In paths to folders and executable files, the presence of a space causes an error. The most common answer is: Enclose the path in quotes. And this answer is not correct. True, some will foam at the mouth and claim that it works. So, two whys appeared - why it is not true and why some will be.

    On Windows (as well as on UNIX), programs installed on the system are registered accordingly by the system. Therefore, some of the installed programs can be launched with one simple command from a BAT file or from the Run applet in the Start panel. One such program is Firefox:

    start firefox

    If after this command you write the path to the executable file, then the following happens: the Firefox browser starts and tries to process the request, that is, the file whose path is specified. That is, if you specify the following:

    start firefox C:\Program Files\Mozilla Firefox\firefox.exe

    The browser will open, no matter what it says after start firefox . That is why some comrades will assure that everything works great. However, if you take portable program, then the situation will be completely different. Let's take as an example Filezilla ftp client. Since the system does not know about the program, the above line

    start filezilla

    won't work. To run a program unknown to the system, you need to specify the path to it:

    start D:\FileZilla\FileZilla.exe

    Long names in bat files

    Now let's talk about paths and spaces. The first way to avoid this problem is to use a short name.

    start C:\Program Files\Sound Club\scw.exe

    In the example there are two names with spaces. Let's replace them with short ones. The rules for creating short names are as follows: the short name uses the first six characters of the name, excluding spaces, after the name the serial number of the folder is indicated using the symbol ~ . Since my Program Files and Sound Club folders are singular, it will look like this:

    Program Files - Progra~1 Sound Club - SoundC~1 start C:\Progra~1 \SoundC~1 \scw.exe

    If there are two folders nearby, for example Sound Club and Sound Clown, then following the rules, in the example above you will need to specify SoundC~2, since in this case Sound Club will be the second name (names are counted in alphabetical order).

    But this method is inconvenient because you have to indicate serial numbers. The situation with Program files is more or less normal. Few people will find two similar folders on the system drive. But if you decide to install multiple Mozilla products on your computer. You will end up with several folders, for example:

    Mozilla Firefox Mozilla Thunderbird Mozilla Sunbird

    Short names for them will be

    Mozill~1 Mozill~2 Mozill~3

    Now imagine that you wrote a BAT file mentioning these programs. If you uninstall Firefox, the remaining entries will no longer work, and if you uninstall Thunderbird, the entry for Sunbird will no longer work. In short, the method with short names- not our way.

    Spaces and quotes in bat files

    Quotes actually work, but not in the ways that are usually advised. The following is usually advised:

    start "C:\Program Files\Sound Club\scw.exe"

    So the command will not work, because if you look at the help for it (start /? ), then in the help you will see the following:

    START ["header"] [command/program] [parameters]

    As you can see, the first parameter is the window title and it is in quotes. This parameter is optional, but it is still recommended to specify it () to avoid errors when executing the command. You don't have to write anything inside the quotes. It will turn out like this:

    start "" "C:\Program Files\Sound Club\scw.exe"

    The option of enclosing all names with spaces separately in quotes will also work:

    start C:\"Program Files"\"Sound Club"\scw.exe

    However, in some cases, none of the above works. In such cases, I can recommend using the cd command. Let's go to system partition, then cd to Program folder Files and run the program (start):

    %SystemDrive% cd \Program Files\Sound Club\ start scw.exe

    I think this method will work everywhere. Now a couple more important points. Let's say you have created a batch file that launches three programs and you need to temporarily exclude the launch of one of the three. This can be done by deleting the line or commenting it out. The first method is vandal, and the second, see below.

    start firefox start jetaudio rem start defraggler

    In this case, the launch of the Defraggler.exe program installed on the system is disabled. Comment lines by specifying the rem command at the beginning of the line. All BAT files are executed in a console window. To make it disappear when the commands are completed, do not forget to write the exit command at the end.

    start firefox start jetaudio rem start defragler exit

    Launching applications from a bat file

    In the first part of the article, I spoke in general terms about BAT files. Now it has become clear what it is and what it is eaten with. In the second part we will talk about more specific things. For example, how to use a BAT file to launch several applications with certain settings or install the program automatically so as not to waste time on answers like You agree to the terms license agreement? and don't press unnecessary buttons.

    Several ways to launch applications using a BAT file were outlined above. The very first one is short command to launch the program installed on the system.

    start firefox

    This doesn't always work. Therefore, this technique can be fully applied on a specific system, but as a universal solution he doesn't fit. If your goal is to make the BAT file work everywhere and always, you need to use full paths:

    start C:\"Program Files"\"Mozilla Firefox"\firefox.exe

    I also noted that the BAT file must contain a command to complete:

    start C:\"Program Files"\"Mozilla Firefox"\firefox.exe exit

    Running programs in bat files with parameters (keys)

    You can not only run the program, but also give it additional commands when starting it. For example, command to run minimized:

    start /min D:\FileZilla\FileZilla.exe exit

    To command in this case means to indicate the key. The key is indicated with a slash after the main command (command /key). The main command in this case is start . True, the min key only works in half the cases, because it relates specifically to the start command, and not to the programs that this command launches.

    In general, there are a lot of keys and sets of keys different programs may vary significantly. There are, however, a few common ones. For example, the help key (/? or /help). To see how this key works, let's look at a practical example. Open the console (Click + R , enter cmd , then Enter ) and type the following in the console:

    start /?

    The console will display a list of valid keys with comments for the start command.

    Pay attention to the /wait switch. In some cases, it is simply irreplaceable. For example, you decided to use a BAT file to unpack the archive with the program and run this very program. The batch file will contain two commands - for unpacking and for launching. Since the commands will be executed almost simultaneously when running the BAT file, the archive will not have time to unpack and there will be nothing to run. Therefore there will be an error. In this case, the key will come to the rescue /wait:

    Thus, the system will first perform the first action, wait for it to complete, and only then proceed to the second. If you need to wait a specific period of time, it is easier to use a console utility. In the right place in the BAT file, write the following command (the number is the number of seconds):

    start Sleep.exe 15

    You can do a lot with keys. It is possible to install applications. To do this, several keys are used depending on the type of installer used to install the program on the computer:

    /S /s /q /silent and a number of others

    In some cases it can be very convenient. Avast Antivirus has the option quiet installation V corporate version. The free (home) version supposedly does not have a silent installation. However, if you know how the InstallShield installer works, you will understand that this is a canard, since this installer itself supports the /S silent installation switch. This means that all products made on its basis do the same. And Avast is no exception. Just create a file with the contents in the folder with Avast's BAT

    start avast.exe /S exit

    you launch it and the program is installed on your computer almost without your participation. This way you can write a whole list of programs for silent installation and save time, for example, on reinstalling the system. In the article you can get more detailed information on the keys.

    There are other options for managing programs using BAT files. You can start a program by telling it to open a file at startup. I use this method when developing websites. It’s very convenient when all your tools open necessary documents and folders with just one click:

    rem connection to ftp server start /min D:\FileZilla\FileZilla.exe "ftp://login:password@server" rem opening index.php in Firefox start C:\"program files"\"mozilla firefox"\firefox.exe "http://localhost/site_folder/index.php" rem opening start.html in a text editor start /min C:\"Program Files"\text_editor.exe "E:\server\site_folder\index.html" rem opening the folder with site files start /min E:\server\folder_with_site rem console exit exit

    I note that all the techniques described above can be used in various combinations and combinations.

    start /min /wait program.exe /m /S start C:\Directory\program2.exe "C:\Files\file.odt" exit

    But it is important to remember: everything related to the execution of the program launched in the batch file is written with it on the same line.

    start C:\"program files"\"mozilla firefox"\firefox.exe "http://localhost/site_folder/index.php"

    As an epilogue, I will offer for your review the converter of BAT files into applications in the .exe format - . A BAT file is not always aesthetically pleasing, but with the help of a converter you can pack a batch file into an exe file, decorating it with any icon of your choice.

    I came across another BAT to EXE converter, you can consider it as an alternative to the previous program: Advanced Bat To Exe Converter

    If you do not need any software installed on your computer the software worked all the time. If you want to save system resources, or just create a distracting environment with just one click, a simple batch file can help you.

    First, let's look at how to create a batch file, For those who are familiar with Windows script, then let's figure out how to use some simple commands to start or stop service resources or stop an application.
    Create a batch file and run the application.
    To create a batch file, all you need to do is create a new, text file with the extension . Bat , and enter any command into the file the same way you would use it on the command line. Then execute the batch file (by, for example, double-clicking on it) and it will run through the commands in the order you wrote in the file. Simple enough?
    If you want to create a new application instance, it must begin with commands. For example, to create a batch file that you created in Notepad and want to open in a new Explorer window, put these two lines in the batch file:

    start notepad
    start explorer c:\path\to\start

    Batch file on console displays each command, so if you want to prevent this you can add an @ symbol before the command to eliminate the extra output, or you can just write this line at the top of the file:
    @ECHO OFF
    Now that we have a few simple basics batch file, let's move on to more useful batch file tasks. (Remember that you can copy and paste any of the commands below into a text file, save it with a .bat extension and you will get a batch file.)
    Stop or Start services in a batch file.
    Many applications these days install a bunch of ancillary services that help the application, but they don't really need to be running all the time. For example, virtual machine software, which often installs a bunch of heavy services that use a lot of extra resources. If you don't use the virtual machine all the time, they really shouldn't be running.
    What can we do This is to create a batch file that stops the services, and also another batch file that starts them back. To do this, you can simply use a pure start or stop command as the first parameter, and then the service name after it. You can use the service with a short name or display name in quotes, as in one of these two examples:
    net stop wuaserv
    NET STOP « Windows Update»
    You can find service names quite easily by opening the Services tool (use the Start menu search to find Services and launch them) and double-click on one of the services. You will see the short name of the service which is underlined in the example below:

    (And another look at the services that are currently running on your system, pull up Manager Windows tasks(Ctrl + Shift + Escape) and go to the Services tab.)
    You can start the service again using the opposite command, like this:
    net start wuaserv

    Note that if you use Windows 7 or Vista and you still have UAC enabled, you need to run the batch file as an administrator to stop the service. You can create a shortcut to a batch file and specify Always Use as Administrator in the shortcut's properties to eliminate the need to right-click every time.
    Kill applications using a batch file
    While stopping services is useful to free up some system resources, you will be able to free up a lot more resources by killing applications that shouldn't be running, which may also not be very useful and distracting notifications and will interfere with your concentration. For example, if you really have to write article, you can create a KillDistractions.bat file that disables all other applications except your favorite text editor.
    To kill applications from the command line or a batch file, all you have to do is use the Taskkill command with the /IM parameter, which matches the name of the image column with the task manager, which is actually just the name of the file with executable file. For example, to kill Notepad you can use the command:

    taskkill /IM notepad . exe

    This command will by default simulate clicking the red X in the corner of the window, so you will be prompted to save your work if necessary. If you want to instantly kill an application without saving, you can use the /F option to not save, for example:
    Taskkill /F /IM notepad.exe
    Taskkill /F /IM chrome.exe
    With the Taskkill command you have many other options to choose from, which can be viewed with the /? parameter. (for example, like Taskkill /?).
    Create a shortcut to run the batch file
    Now that we've done the basic commands that you would create in a batch file that starts or stops all the services and applications that we don't want running, we can do in last line batch file launch applications when we plan to start working, then configure the shortcut to launch the batch file, minimize the command prompt window on the screen. So right-click on the desktop or in any Explorer window, go to New -> “Shortcut” and specify the path to your batch script in it.

    If you press the button in the context window“Advanced” you can specify, if necessary, to run the application with administrator rights. If you are stopping a service in a batch file, you will need to use this option, although it should be noted that any applications you write to the batch file will also run as administrator. But, if you have disabled UAC, this will not matter.
    Putting it all together
    Now you know how to stop services, kill applications, and create proper shortcuts, it's time to put it all together in useful combinations. Here's an example script I use to kill distracting apps to go into recording mode, but you can customize it as you see fit whenever you might need something.
    Taskkill /IM tweetdeck.exe
    Taskkill /IM chrome.exe
    Taskkill /IM firefox.exe
    Taskkill /IM pidgin.exe
    Taskkill /IM notepad.exe
    Since I often use a virtual machine, to test it, I also created batch files, which start and stop the service when needed to make sure I'm not wasting resources when I actually need the virtual machine running. To stop the service I created a file called stopvmware.bat, although there is also a collection of all these services to manually boot, so I only used this after I close VMware.
    NET STOP VMAuthdService
    NET STOP VMnetDHCP
    NET STOP "VMware NAT Service"
    NET STOP "VMUSBArbService"
    Then, when I need to start VMware again, I can simply use my startvmware.bat file, which starts the service and then starts the VMware application.
    NET START VMAuthdService
    NET START VMnetDHCP
    NET START "VMware NAT Service"
    NET START "VMUSBArbService"
    Start "C:\Program Files (x86)\VMware\ VMware Workstation\vmware.exe"
    You can customize these scripts, to do whatever you want, this should give your tool the tools you need to start creating your own time-saving batch files.