In this chapter, we will look at some of the frequently used batch commands.
In this chapter, we will learn how to create, save, execute, and modify batch files.
Рассмотрим мощный инструмент автоматизации рутинных задач в семействе операционных систем Windows.
Starting a New Process
DOS scripting also has the availability to start a new process altogether. This is achieved by using the START command.
Syntax
START "title" [/D path] [options] "command" [parameters]
title
− Text for the CMD window title bar (required.)path
− Starting directory.command
− The command, batch file or executable program to run.parameters
− The parameters passed to the command.
Examples
START "Test Batch Script" /Min test.bat
The above command will run the batch script test.bat in a new window. The windows will start in the minimized mode and also have the title of “Test Batch Script”.
START "" "C:\Program Files\Microsoft Office\Winword.exe" "D:\test\TESTA.txt"
The above command will actually run Microsoft word in another process and then open the file TESTA.txt in MS Word.
Что такое bat-файлы?
BAT-файл — это последовательность команд для интерпретатора командной строки в виде текстового файла с расширением .bat или .cmd. Основное предназначение пакетных файлов — автоматизация рутинных действий пользователя компьютера.
Название BAT появилось от английского batch — пакетная обработка. В истории продуктов Microsoft пакетные файлы существовали с первой версии MS-DOS в 80-х годах и позже успешно интегрировались в Microsoft Windows. В MS-DOS командным интерпретатором выступает COMMAND. COM, а начиная с Windows NT и до сих пор используется CMD. EXE.
Интерпретатор COMMAND. COM принимает файлы с расширением . BAT. Расширение . CMD создано для интерпретатора CMD. EXE с целью различать файлы для «старого» и «нового» интерпретаторов. C MD. EXE корректно обрабатывает оба расширения.
Интерпретатор CMD. EXE является частью современных операционных систем семейства Microsoft Windows, несмотря на отсутствие развития с начала 2000-х.
Batch Script – Overview
Batch Script is incorporated to automate command sequences which are repetitive in nature. Scripting is a way by which one can alleviate this necessity by automating these command sequences in order to make one’s life at the shell easier and more productive. In most organizations, Batch Script is incorporated in some way or the other to automate stuff.
Some of the features of Batch Script are −
Has control structures such as for, if, while, switch for better automating and scripting.
Supports advanced features such as Functions and Arrays.
Supports regular expressions.
Can include other programming codes such as Perl.
Some of the common uses of Batch Script are −
Setting up servers for different purposes.
Automating housekeeping activities such as deleting unwanted files or log files.
Automating the deployment of applications from one environment to another.
Installing programs on various machines at once.
Batch scripts are stored in simple text files containing lines with commands that get executed in sequence, one after the other. These files have the special extension BAT or CMD. Files of this type are recognized and executed through an interface (sometimes called a shell) provided by a system file called the command interpreter. On Windows systems, this interpreter is known as cmd.exe.
:: Deletes All files in the Current Directory With Prompts and Warnings ::(Hidden, System, and Read-Only Files are Not Affected) :: @ECHO OFF DEL . D R
Основы взаимодействия с bat-файлами
Пакетный файл bat — это текстовый документ со специальным расширением. Для создания своего первого bat-файла достаточно «Блокнота», который доступен в операционной системе. To improve the convenience of writing and supporting bat files, we recommend using Notepad++ or any other text editor with syntax highlighting.
Creation of bat files
If you make a mistake when saving and the batch file is saved with the extension txt, then it is not necessary to save again. You can turn on the display of the file name extension and rename the file.
Run bat files
Run batch files by double clicking on the icon. Additionally, you can use the command Open
from the context menu, which is available by clicking the right mouse button (RMB) on the file. If administrator rights are required to execute commands, then in the same context menu there is an item Run as administrator
.
Executable bat files cannot ask for admin rights if commands need extended rights.
Launching through the context menu will open a command interpreter in which the commands of the bat file will be executed. When the commands complete, the window will close. This behavior is not acceptable if some kind of feedback is required from the batch file, such as an error message or the result of a calculation. In this case, the interpreter must be started manually and passed a batch file to it.
To launch the command line interpreter, open the menu Run
keyboard shortcut Win + R, enter cmd
and press OK
.
To run a batch file, move it with the mouse to the window that opens and press Enter
. The bat-file commands will be executed, and you will see its output on the screen.
Regardless of the launch method, a window will open that may attract attention and annoy. To run in “stealth” mode, you must use another Microsoft Windows scripting language – VBScript.
By analogy, create a file with the .vbs extension and fill it with the following commands:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr & "С:\путь\до\вашего\скрипта.bat" & Chr, 0
Set WshShell = Nothing
For a hidden launch, you should run the created file, not the bat file. The hidden launch of a bat file is relevant for automating scheduled actions, for example, creating a backup.
Modifying Batch Files
Step 1
− Open windows explorer.Step 2
− Go to the location where the .bat or .cmd file is stored.Step 3
− Right-click the file and choose the “Edit” option from the context menu. The file will open in Notepad for further editing.
Deleting files
Programs and users leave traces of work in the form of files that are not deleted automatically. Fortunately, the cleaning process can be automated.
Let’s assume that during the user’s work a large number of jpeg files are generated that need to be deleted. The FOR loop operator comes to the rescue.
rem Ищем все файлы с расширением jpeg в каталоге work
rem Ключ /r включает в поиск все подкаталоги в каталоге work
for /r work %%file in (*.jpeg) do (
rem Выводим имя файла
echo %%file
delete %%i
)
Output
C:\>test.bat 10 2 4 6 8 10 22 Press any key to continue .
Batch Script – Strings
In DOS, a string is an ordered collection of characters, such as “Hello, World!”.
TIME
This command sets or displays the time.
Syntax
TIME
Example
@echo off echo %TIME%
Output
The current system time will be displayed. For example,
22:06:52.87
Batch Script – Registry
The Registry is one of the key elements on a windows system. It contains a lot of information on various aspects of the operating system. Almost all applications installed on a windows system interact with the registry in some form or the other.
The Registry contains two basic elements: keys and values. Registry keys
are container objects similar to folders. Registry values
are non-container objects similar to files. Keys may contain values or further keys. Keys are referenced with a syntax similar to Windows’ path names, using backslashes to indicate levels of hierarchy.
This chapter looks at various functions such as querying values, adding, deleting and editing values from the registry.
Logging the error messages to another file
net statistics /Server
The command given in the .bat file is wrong. Let us log the message and see what we get.
C:\>test.bat > testlog.txt 2> testerrors.txt
The file testerrors.txt will display the error messages as shown below:
The option /SERVER is unknown. The syntax of this command is: NET STATISTICS [WORKSTATION | SERVER] More help is available by typing NET HELPMSG 3506.
Looking at the above file the developer can fix the program and execute again.
Batch Script – Printing
Printing can also be controlled from within Batch Script via the NET PRINT command.
Syntax
PRINT [/D:device] [[drive:][path]filename[.]]
Where /D:device – Specifies a print device.
Example
print c:\example.txt /c /d:lpt1
The above command will print the example.txt file to the parallel port lpt1.
Using pause command
Another way is to pause the batch execution when there is an error. When the script is paused, the developer can fix the issue and restart the processing.
In the example below, the batch script is paused as the input value is mandatory and not provided.
Comments Using the
Syntax
:: Remarks
where ‘Remarks’ is the comment which needs to be added.
Example
@echo off :: This program just displays Hello World set message = Hello World echo %message%
Output
Hello World
Note
− If you have too many lines of Rem, it could slow down the code, because in the end each line of code in the batch file still needs to be executed.
Let’s look at the example of the large script we saw at the beginning of this topic and see how it looks when documentation is added to it.
::=============================================================== :: The below example is used to find computer and logged on users :: ::=============================================================== ECHO OFF :: Windows version check IF NOT "%OS%"=="Windows_NT" GOTO Syntax ECHO.%* | FIND "?" >NUL :: Command line parameter check IF NOT ERRORLEVEL 1 GOTO Syntax IF NOT [%2]==[] GOTO Syntax :: Keep variable local SETLOCAL :: Initialize variable SET WSS= :: Parse command line parameter IF NOT [%1]==[] FOR /F "tokens = 1 delims = \ " %%A IN ('ECHO.%~1') DO SET WSS = %%A :: Use NET VIEW and NBTSTAT to find computers and logged on users FOR /F "tokens = 1 delims = \ " %%a IN ('NET VIEW ^| FIND /I "\\%WSS%"') DO FOR /F "tokens = 1 delims = " %%A IN ('NBTSTAT -a %%a ^| FIND /I /V "%%a" ^| FIND "<03>"') DO ECHO.%%a %%A :: Done ENDLOCAL GOTO:EOF :Syntax ECHO Display logged on users and their workstations. ECHO Usage: ACTUSR [ filter ] IF "%OS%"=="Windows_NT" ECHO Where: filter is the first part of the computer name^(s^) to be displayed
Working with Numeric Values
In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch.
@echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c%
We are first setting the value of 2 variables, a and b to 5 and 10 respectively.
We are adding those values and storing in the variable c.
Finally, we are displaying the value of the variable c.
The output of the above program would be 15.
@echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% SET /A c = %a% - %b% echo %c% SET /A c = %b% / %a% echo %c% SET /A c = %b% * %a% echo %c%
15 -5 2 50
Using ErrorLevel to detect errors and log them
Errorlevel returns 0 if the command executes successfully and 1 if it fails.
@echo off PING google.com if errorlevel 1 GOTO stop :stop echo Unable to connect to google.com pause
During execution, you can see errors as well as logs:
C:\>test.bat > testlog.txt
Pinging google.com [172.217.26.238] with 32 bytes of data: Reply from 172.217.26.238: bytes=32 time=160ms TTL=111 Reply from 172.217.26.238: bytes=32 time=82ms TTL=111 Reply from 172.217.26.238: bytes=32 time=121ms TTL=111 Reply from 172.217.26.238: bytes=32 time=108ms TTL=111 Ping statistics for 172.217.26.238: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 82ms, Maximum = 160ms, Average = 117ms Connected successfully Press any key to continue . . .
Ping request could not find host google.com. Please check the name and try again. Unable to connect to google.com Press any key to continue . . .
Killing a Particular Process
Syntax
TASKKILL [/S system [/U username [/P [password]]]] { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]
Examples
taskkill /f /im notepad.exe
The above command kills the open notepad task, if open.
taskill /pid 9214
The above command kills a process which has a process of 9214.
Rename files
Renaming files in Windows is done with the RENAME command. However, this team has its own characteristics.
First, renaming is possible only within one disk and one directory. You can move between directories on the same disk, but copy only between different disks.
rename abc.txt cba.txt
Secondly, renaming by mask is possible. Let’s say there is a list of photos photo000.jpeg, photo001.jpeg and so on. You need to change the prefix from photo to mobile.
rename photo* mobile*
If there are other files with the photo prefix in the current directory, and only images with the jpeg extension need to be renamed, then the command is modified:
rename photo*.jpeg mobile*.jpeg
Loops
In the decision making chapter, we have seen statements which have been executed one after the other in a sequential manner. Additionally, implementations can also be done in Batch Script to alter the flow of control in a program’s logic. They are then classified into flow of control statements.
Error Level
The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script.
Syntax
IF %ERRORLEVEL% NEQ 0 ( DO_Something )
It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file.
EXIT /B at the end of the batch file will stop execution of a batch file.
Use EXIT /B at the end of the batch file to return custom return codes.
Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed. In the batch file, it is always a good practice to use environment variables instead of constant values, since the same variable get expanded to different values on different computers.
Let’s look at a quick example on how to check for error codes from a batch file.
Example
if not exist c:\lists.txt exit 7 if not defined userprofile exit 9 exit 0
Call Find.cmd if errorlevel gtr 0 exit echo "Successful completion"
Output
If the file c:\lists.txt does not exist, then nothing will be displayed in the console output.
If both of the above condition passes then the string “Successful completion” will be displayed in the command prompt.
Executing Batch Files
Step 1
− Open the command prompt (cmd.exe).Step 2
− Go to the location where the .bat or .cmd file is stored.
Working with Environment Variables
@echo off echo %JAVA_HOME%
C:\Atlassian\Bitbucket\4.0.1\jre
Batch Script – Functions
A function is a set of statements organized together to perform a specific task. In batch scripts, a similar approach is adopted to group logical statements together to form a function.
Function Declaration
− It tells the compiler about a function’s name, return type, and parameters.Function Definition
− It provides the actual body of the function.
Batch Script – Debugging
Debugging a batch script becomes important when you are working on a big complex batch script.
Scheduled launch
Responsible for the execution of scheduled actions Task Scheduler
. Open the menu Run
and run the program taskschd.msc
.
Select an item Create a simple task
and fill in the task parameters:
- name for easy identification,
- frequency and start time,
- action – Run the program,
- program or script – the path to your .bat file or .vbs file that runs the .bat file invisibly.
Please note that the scheduler allows you not only to perform an action on time, but also when an event occurs – for example, when the computer boots up. This approach is an alternative to autoloading.
In the case of developing your own bat-file, you should familiarize yourself with the basics of the command interpreter.
Batch Script – Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
- Arithmetic operators
- Relational operators
- Logical operators
- Assignment operators
- Bitwise operators
Iterating Over an Array
@echo off setlocal enabledelayedexpansion set topic[0] = comments set topic[1] = variables set topic[2] = Arrays set topic[3] = decision making set topic[4] = Time and date set topic[5] = Operators for /l %%n in (0,1,5) do ( echo !topic[%%n]! )
Each element of the array needs to be specifically defined using the set command.
The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array.
Output
Comments variables Arrays decision making Time and date Operators
Length of an Array
The length of an array is done by iterating over the list of values in the array since there is no direct function to determine the number of elements in an array.
@echo off set Arr[0] = 1 set Arr[1] = 2 set Arr[2] = 3 set Arr[3] = 4 set "x=0" :SymLoop if defined Arr[%x%] ( call echo %%Arr[%x%]%% set /a "x+=1" GOTO :SymLoop ) echo "The length of the array is" %x%
Output
The length of the array is 4
Command Line Arguments
Batch scripts support the concept of command line arguments if arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on.
@echo off echo %1 echo %2 echo %3
If the above batch script is stored in a file called test.bat and we were to run the batch as
Test.bat 1 2 3
1 2 3
If we were to run the batch as
Example 1 2 3 4
The output would still remain the same as above. However, the fourth parameter would be ignored.
Batch Script – Comments
It’s always a good practice to add comments or documentation for the scripts which are created. This is required for maintenance of the scripts to understand what the script actually does.
ECHO OFF IF NOT "%OS%"=="Windows_NT" GOTO Syntax ECHO.%* | FIND "?" >NUL IF NOT ERRORLEVEL 1 GOTO Syntax IF NOT [%2]==[] GOTO Syntax SETLOCAL SET WSS= IF NOT [%1]==[] FOR /F "tokens = 1 delims = \ " %%A IN ('ECHO.%~1') DO SET WSS = %%A FOR /F "tokens = 1 delims = \" %%a IN ('NET VIEW ^| FIND /I "\\%WSS%"') DO FOR /F "tokens = 1 delims = " %%A IN ('NBTSTAT -a %%a ^| FIND /I /V "%%a" ^| FIND ""') DO ECHO.%%a %%A ENDLOCAL GOTO:EOF ECHO Display logged on users and their workstations. ECHO Usage: ACTUSR [filter] IF "%OS%"=="Windows_NT" ECHO Where: filter is the first part of the computer name^(s^) to be displayed
Local vs Global Variables
In any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed.
Example
@echo off set globalvar = 5 SETLOCAL set var = 13145 set /A var = %var% + 5 echo %var% echo %globalvar% ENDLOCAL
Few key things to note about the above program.
The ‘globalvar’ is defined with a global scope and is available throughout the entire script.
Output
13150 5
Modifying an Array
To add an element to the end of the array, you can use the set element along with the last index of the array element.
Example
@echo off set a[0] = 1 set a[1] = 2 set a[2] = 3 Rem Adding an element at the end of an array Set a[3] = 4 echo The last element of the array is %a[3]%
The last element of the array is 4
@echo off set a[0] = 1 set a[1] = 2 set a[2] = 3 Rem Setting the new value for the second element of the array Set a[1] = 5 echo The new value of the second element of the array is %a[1]%
The new value of the second element of the array is 5
Команды и синтаксис пакетных файлов
Командный интерпретатор выполняет команды из файла последовательно — строка за строкой. Исключение составляет только оператор GOTO, который «отправляет» к указанной строке. Командный интерпретатор выполняет два вида команд: встроенные команды и внешние исполняемые файлы.
Внешние исполняемые файлы — это любой исполняемый файл, то есть с расширением EXE, CMD или BAT, который доступен в операционной системе. Например, «Блокнот» — это исполняемый файл notepad.exe. Следующая команда приведет к запуску этого приложения с открытым файлом C:\1.txt:
notepad.exe C:\1.txt
Аргументом может быть не только путь, но и ключ — специальный аргумент, который начинается с символа слэш (/). У каждой программы свой «реестр» ключей и их значений.
Обратите внимание, что не все внешние команды «понимают» аргументы, переданные из интерпретатора командной строки. Например, исполняемый файл приложения калькулятор, calc.exe, игнорирует все аргументы командной строки. Внешним исполняемым файлом может быть в том числе другой bat-файл.
Встроенные команды — это команды, которые являются частью интерпретатора командной строки. Полный список команд доступен по команде HELP. Данные команды не имеют отдельного исполняемого файла.
Иногда в имени файла или каталога встречаются пробелы. Наиболее очевидный пример — каталог Program Files на диске C. В этом случае помогают кавычки. Их можно расставить различными способами. Например:
cd "C:\Program Files\123"
cd C:\”Program Files”\123
Операционная система Windows запрещает использование множества специальных символов в именах файлов, в том числе кавычки, поэтому проблем с указанием файлов не возникнет.
Официальный способ — команда rem или два двоеточия.
rem Это первый комментарий
:: Это тоже комментарий
goto start
===
Здесь можно оставить большой комментарий,
лицензию или даже ASCII-арт
===
:start
В конце комментария задаем имя метки, а в начале комментария выполняем команду GOTO c именем метки. Этот способ требует внимания, так как для каждого комментария должна быть своя метка, иначе выполнение bat-файла может отличаться от ожидания разработчика.
Syntax
test.bat > testlog.txt 2> testerrors.txt
Viewing the List of Running Processes
In Batch Script, the TASKLIST command can be used to get the list of currently running processes within a system.
Syntax
TASKLIST [/S system [/U username [/P [password]]]] [/M [module] | /SVC | /V] [/FI filter] [/FO format] [/NH]
Examples
TASKLIST
Image Name PID Session Name Session# Mem Usage ========================= ======== ================ =========== ============ System Idle Process 0 Services 0 4 K System 4 Services 0 272 K smss.exe 344 Services 0 1,040 K csrss.exe 528 Services 0 3,892 K csrss.exe 612 Console 1 41,788 K wininit.exe 620 Services 0 3,528 K winlogon.exe 648 Console 1 5,884 K services.exe 712 Services 0 6,224 K lsass.exe 720 Services 0 9,712 K svchost.exe 788 Services 0 10,048 K svchost.exe 832 Services 0 7,696 K dwm.exe 916 Console 1 117,440 K nvvsvc.exe 932 Services 0 6,692 K nvxdsync.exe 968 Console 1 16,328 K nvvsvc.exe 976 Console 1 12,756 K svchost.exe 1012 Services 0 21,648 K svchost.exe 236 Services 0 33,864 K svchost.exe 480 Services 0 11,152 K svchost.exe 1028 Services 0 11,104 K svchost.exe 1048 Services 0 16,108 K wlanext.exe 1220 Services 0 12,560 K conhost.exe 1228 Services 0 2,588 K svchost.exe 1276 Services 0 13,888 K svchost.exe 1420 Services 0 13,488 K spoolsv.exe 1556 Services 0 9,340 K
tasklist > process.txt
The above command takes the output displayed by tasklist and saves it to the process.txt file.
tasklist /fi "memusage gt 40000"
Image Name PID Session Name Session# Mem Usage ========================= ======== ================ =========== ============ dwm.exe 916 Console 1 127,912 K explorer.exe 2904 Console 1 125,868 K ServerManager.exe 1836 Console 1 59,796 K WINWORD. EXE 2456 Console 1 144,504 K chrome.exe 4892 Console 1 123,232 K chrome.exe 4976 Console 1 69,412 K chrome.exe 1724 Console 1 76,416 K chrome.exe 3992 Console 1 56,156 K chrome.exe 1168 Console 1 233,628 K chrome.exe 816 Console 1 66,808 K
Deleting an Alias
An alias or macro can be deleted by setting the value of the macro to NULL.
Example
@echo off doskey cd = cd/test doskey d = dir d=
In the above example, we are first setting the macro d to d = dir. After which we are setting it to NULL. Because we have set the value of d to NULL, the macro d will deleted.
Batch Script – Aliases
Aliases means creating shortcuts or keywords for existing commands. Suppose if we wanted to execute the below command which is nothing but the directory listing command with the /w option to not show all of the necessary details in a directory listing.
Dir /w
dw = dir /w
When we want to execute the dir /w
command, we can simply type in the word dw
. The word ‘dw’ has now become an alias to the command Dir /w.
Output
C:\>test.bat input value not provided Press any key to continue.
Примеры bat-файлов
Рассмотрим несколько примеров bat-файлов. Начнем с базовых команд.
Обновление IP-адреса
ipconfig /renew
Данная команда генерирует много текстового вывода, который может испугать неподготовленного пользователя. Сама команда также может быть непривлекательной. Поэтому отключим отображение команды и перенаправим вывод выполнения в «никуда». Вместо слова NUL может быть любое имя или путь. Тогда вывод будет перенаправлен в указанный файл.
rem Отключаем отображение команд. Символ @ отключает отображение текущей команды
@echo off
rem Переводим вывод выполнения в устройство NUL, вывод исчезнет
ipconfig /renew > NUL
При запуске такого скрипта появляется черное окно, которое быстро исчезает. Можно оставить простые и понятные пользователю сообщения и не дать окну закрыться.
@echo off
echo Выполняется настройка, пожалуйста, подождите...
ipconfig /renew > NUL
echo Все хорошо.
rem Эта команда остановит выполнение до тех пор, пока пользователь не нажмет любую клавишу
pause
Скорее всего данный скрипт выведет набор непонятных символов вместо сообщения. Дело в том, что в русскоязычных ОС Windows по умолчанию в CMD. EXE используется кодировка CP866. Блокнот сохраняет в CP1251 (Windows-1251), а Notepad++ — в UTF-8. Для решения проблемы необходимо сменить кодировку интерпретатора командой chcp или сохранить bat-файл в кодировке интерпретатора.
rem Смена кодировки на Windows-1251
chcp 1251 > NUL
rem Смена кодировки на UTF-8
chcp 65001 > NUL
Я сохранил файл в кодировке UTF-8 и итоговый скрипт получился таким:
@echo off
chcp 65001 > NUL
echo Выполняется настройка, пожалуйста, подождите...
ipconfig /renew > NUL
echo Все хорошо.
pause
Создание резервной копии каталога
Перейдем к более жизненной ситуации — создание резервной копии (backup) каталога. Предположим, что каждый архив должен иметь в названии дату создания копии. Создадим каталог, имя которого — текущая дата. Текущая дата хранится в переменной DATE. Для обращения к переменным название переменной помещается между знаками процента.
mkdir %DATE%
cd %DATE%
Копирование файлов в текущий каталог производится командой COPY.
rem файлы 1.txt и 2.txt будут скопированы в текущую папку
COPY C:\1.txt C:\2.txt .
rem файл 3.txt будет сохранен в текущую папку как example.txt
COPY C:\1.txt .\example.txt
Возможно, в резервную копию необходимо дополнить служебную информацию — например, список файлов в корне копии и имя компьютера.
rem Имя компьютера записывается в файл computer.txt
hostname > computer.txt
rem Список файлов в текущем каталоге записывается в files.txt
dir . > files.txt
Обычно резервные копии хранят в zip- или rar-архивах. Из командной строки отлично управляется архиватор 7z.
cd ..
7z -tzip a backup.zip %DATE%
Relational Operators
Relational operators allow of the comparison of objects. Below are the relational operators available.
Example
@echo off if [%1] == [] ( echo input value not provided goto stop ) else ( echo "Valid value" ) :stop pause
Example
@echo off if [%1] == [] ( echo input value not provided goto stop ) rem Display numbers for /l %%n in (2,2,%1) do ( echo %%n ) :stop pause
Suppressing Program Output
Dir C:\ > NUL
Stdin
To work with the Stdin, you have to use a workaround to achieve this. This can be done by redirecting the command prompt’s own stdin, called CON.
TYPE CON > lists.txt
Creating an Array
set a[0]=1
Where 0 is the index of the array and 1 is the value assigned to the first element of the array.
Example
@echo off set list = 1 2 3 4 (for %%a in (%list%) do ( echo %%a ))
Output
1 2 3 4
Saving Batch Files
After your batch file is created, the next step is to save your batch file. Batch files have the extension of either .bat or .cmd. Some general rules to keep in mind when naming batch files −
Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts.
Don’t name them after common batch files which are available in the system such as ping.cmd.
The above screenshot shows how to save the batch file. When saving your batch file a few points to keep in mind.
- Remember to put the .bat or .cmd at the end of the file name.
- Choose the “Save as type” option as “All Files”.
- Put the entire file name in quotes “”.
Batch Script – Commands
In this chapter, we will look at some of the frequently used batch commands.
Batch Script – Files
In this chapter, we will learn how to create, save, execute, and modify batch files.
Batch Script – Environment
This chapter explains the environment related to Batch Script.
Creating Batch Files
:: Deletes All files in the Current Directory With Prompts and Warnings ::(Hidden, System, and Read-Only Files are Not Affected) :: @ECHO OFF DEL . DR
Command Line Printer Control
As of Windows 2000, many, but not all, printer settings can be configured from Windows’s command line using PRINTUI. DLL and RUNDLL32. EXE
Syntax
RUNDLL32. EXE PRINTUI. DLL,PrintUIEntry [ options ] [ @ commandfile ]
Creating Structures in Arrays
Example
@echo off set len = 3 set obj[0]. Name = Joe set obj[0]. ID = 1 set obj[1]. Name = Mark set obj[1]. ID = 2 set obj[2]. Name = Mohan set obj[2]. ID = 3 set i = 0 :loop if %i% equ %len% goto :eof set cur. Name= set cur. ID= for /f "usebackq delims==.tokens=1-3" %%j in (`set obj[%i%]`) do ( set cur.%%k=%%l ) echo Name = %cur. Name% echo Value = %cur. ID% set /a i = %i%+1 goto loop
Each variable defined using the set command has 2 values associated with each index of the array.
The variable i
is set to 0 so that we can loop through the structure will the length of the array which is 3.We always check for the condition on whether the value of i is equal to the value of len
and if not, we loop through the code.
Output
Name = Joe Value = 1 Name = Mark Value = 2 Name = Mohan Value = 3
Testing if a Printer Exists
There can be cases wherein you might be connected to a network printer instead of a local printer. In such cases, it is always beneficial to check if a printer exists in the first place before printing.
The existence of a printer can be evaluated with the help of the RUNDLL32. EXE PRINTUI. DLL which is used to control most of the printer settings.
Example
SET PrinterName = Test Printer SET file=%TEMP%\Prt.txt RUNDLL32. EXE PRINTUI. DLL,PrintUIEntry /Xg /n "%PrinterName%" /f "%file%" /q IF EXIST "%file%" ( ECHO %PrinterName% printer exists ) ELSE ( ECHO %PrinterName% printer does NOT exists )
It will first set the printer name and set a file name which will hold the settings of the printer.
The RUNDLL32. EXE PRINTUI. DLL commands will be used to check if the printer actually exists by sending the configuration settings of the file to the file Prt.txt
First Batch Script Program
The Rem command is used to add a comment to say what exactly this batch file does.
The dir command is used to take the contents of the location C:\Program Files.
The ‘>’ command is used to redirect the output to the file C:\lists.txt.
@echo off Rem This is for listing down all the files in the directory Program files dir "C:\Program Files" > C:\lists.txt echo "The program has completed"
When the above command is executed, the names of the files in C:\Program Files will be sent to the file C:\Lists.txt and in the command prompt the message “The program has completed” will be displayed.
Date in Format Year-Month-Day
Example
@echo off echo/Today is: %year%-%month%-%day% goto :EOF setlocal ENABLEEXTENSIONS set t = 2&if "%date%z" LSS "A" set t = 1 for /f "skip=1 tokens = 2-4 delims = (-)" %%a in ('echo/^|date') do ( for /f "tokens = %t%-4 delims=.-/ " %%d in ('date/t') do ( set %%a=%%d&set %%b=%%e&set %%c=%%f)) endlocal&set %1=%yy%&set %2=%mm%&set %3=%dd%&goto :EOF
Output
Today is: 2015-12-30
Batch Script – Devices
Windows now has an improved library which can be used in Batch Script for working with devices attached to the system. This is known as the device console – DevCon.exe.
Windows driver developers and testers can use DevCon to verify that a driver is installed and configured correctly, including the proper INF files, driver stack, driver files, and driver package. You can also use the DevCon commands (enable, disable, install, start, stop, and continue) in scripts to test the driver. DevCon
is a command-line tool that performs device management functions on local computers and remote computers.
%WindowsSdkDir%\tools\x64\devcon.exe %WindowsSdkDir%\tools\x86\devcon.exe %WindowsSdkDir%\tools\arm\devcon.exe
Syntax
devcon [/m:\\computer] [/r] command [arguments]
Examples
List all driver files
devcon driverfiles * > driverfiles.txt
devcon status * > status.txt
devcon /r enable = Printer
devcon /r install c:\windows\inf\keyboard.inf *PNP030b
devcon scan
devcon rescan
Batch Script – Network
Batch script has the facility to work with network settings. The NET command is used to update, fix, or view the network or network settings. This chapter looks at the different options available for the net command.
Batch Script – Process
In this chapter, we will discuss the various processes involved in Batch Script.
Accessing Arrays
You can retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array.
Example
@echo off set a[0]=1 echo %a[0]%
@echo off set a[0] = 1 set a[1] = 2 set a[2] = 3 echo The first element of the array is %a[0]% echo The second element of the array is %a[1]% echo The third element of the array is %a[2]%
The first element of the array is 1 The second element of the array is 2 The third element of the array is 3
Set Command
Syntax
set /A variable-name=value
variable-name
is the name of the variable you want to set.value
is the value which needs to be set against the variable./A –
This switch is used if the value needs to be numeric in nature.
Example
@echo off set message=Hello World echo %message%
In the above code snippet, a variable called message is defined and set with the value of “Hello World”.
To display the value of the variable, note that the variable needs to be enclosed in the % sign.
Output
Hello World
Modifying Batch Files
Step 1
− Open windows explorer.
Step 2
Comments Using the Rem Statement
Syntax
Rem Remarks
where ‘Remarks’ is the comments which needs to be added.
Example
@echo off Rem This program just displays Hello World set message=Hello World echo %message%
Output
Hello World
Saving Batch Files
After your batch file is created, the next step is to save your batch file. Batch files have the extension of either .bat or .cmd. Some general rules to keep in mind when naming batch files −
Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts.
Don’t name them after common batch files which are available in the system such as ping.cmd.
The above screenshot shows how to save the batch file. When saving your batch file a few points to keep in mind.
- Remember to put the .bat or .cmd at the end of the file name.
- Choose the “Save as type” option as “All Files”.
- Put the entire file name in quotes “”.
Batch Script - Decision Making
Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true
, and optionally, other statements to be executed if the condition is determined to be false
.
Batch Script - Arrays
- Each element of the array needs to be defined with the set command.
- The ‘for’ loop would be required to iterate through the values of the array.
Creating Batch Files
:: Deletes All files in the Current Directory With Prompts and Warnings ::(Hidden, System, and Read-Only Files are Not Affected) :: @ECHO OFF DEL . DR
Batch Script - Input / Output
There are three universal “files” for keyboard input, printing text on the screen and printing errors on the screen. The “Standard In” file, known as stdin
, contains the input to the program/script. The “Standard Out” file, known as stdout
, is used to write output for display on the screen. Finally, the “Standard Err” file, known as stderr
, contains any error messages for display on the screen.
Each of these three standard files, otherwise known as the standard streams, are referenced using the numbers 0, 1, and 2. Stdin is file 0, stdout is file 1, and stderr is file 2.
Executing Batch Files
Step 1
− Open the command prompt (cmd.exe).Step 2
− Go to the location where the .bat or .cmd file is stored.
Batch Script - Logging
Logging in is possible in Batch Script by using the redirection command.
Creating an Alias
Alias are managed by using the doskey
command.
Syntax
DOSKEY [options] [macroname=[text]]
macroname
− A short name for the macro.- text
− The commands you want to recall.
Example
@echo off
doskey cd = cd/test
doskey d = dir
Once you execute the command, you will able to run these aliases in the command prompt.
Output
Looping through Command Line Arguments
Example
@ECHO OFF :Loop IF "%1"=="" GOTO completed FOR %%F IN (%1) DO echo %%F SHIFT GOTO Loop :completed
Output
1
2
3
Output
If the command with the above test.bat file is run as test.bat > testlog.txt 2> testerrors.txt The option /SERVER is unknown.The syntax of this command is −
NET STATISTICS [WORKSTATION | SERVER]
More help is available by typing NET HELPMSG 3506.
C:\tp>net statistics /Server
Example
net statistics /Server
The above command has an error because the option to the net statistics command is given in the wrong way.
Logical Operators
The batch language is equipped with a full set of Boolean logic operators like AND, OR, XOR, but only for binary numbers. Neither are there any values for TRUE or FALSE. The only logical operator available for conditions is the NOT operator.
DATE
This command gets the system date.
Syntax
DATE
Example
@echo off echo %DATE%
Output
The current date will be displayed in the command prompt. For example,
Mon 12/28/2015
Replacing an Alias
An alias or macro can be replaced by setting the value of the macro to the new desired value.
Example
@echo off doskey cd = cd/test doskey d = dir d = dir /w
In the above example, we are first setting the macro d to d = dir. After which we are setting it to dir /w. Since we have set the value of d to a new value, the alias ‘d’ will now take on the new value.
Writing and Executing
Typically, to create a batch file, notepad is used. This is the simplest tool for creation of batch files. Next is the execution environment for the batch scripts. On Windows systems, this is done via the command prompt or cmd.exe. All batch files are run in this environment.
Method 1
− Go to C:\Windows\System32 and double click on the cmd file.
Batch Script - Variables
There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command.
Совместимость с MS-DOS
В старых ОС, таких как MS-DOS, было ограничение на отображение имени файлов. На экран выводилось восемь символов имени, точка и три символа расширения. Если имя файла превышало по длине восемь символов, то имя файла отображалось по следующей схеме:
<первые шесть символов имени>~<порядковый номер>
Например, каталог Program Files выглядит следующим образом:
Progra~1
В современных операционных системах такое отображение не применяется, но CMD. EXE до сих пор поддерживает такие запросы к файлам и каталогам.
Выберите подходящий из более 100 готовых конфигураций.
Redirecting Output (Stdout and Stderr)
Dir C:\ > list.txt
In the above example, the stdout
of the command Dir C:\ is redirected to the file list.txt.
If you append the number 2 to the redirection filter, then it would redirect the stderr
to the file lists.txt.
Dir C:\ 2> list.txt
DIR C:\ > lists.txt 2>&1
ECHO Command
@echo off
Batch Script - Return Code
By default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number. We will then use the error number to determine what the error is about and resolve it accordingly.
Function Definition
In Batch Script, a function is defined by using the label statement. When a function is newly defined, it may take one or several values as input 'parameters' to the function, process the functions in the main body, and pass back the values to the functions as output 'return types'.
Every function has a function name, which describes the task that the function performs. To use a function, you "call" that function with its name and pass its input values (known as arguments) that matches the types of the function's parameters.
:function_name Do_something EXIT /B 0
The function_name is the name given to the function which should have some meaning to match what the function actually does.
The EXIT statement is used to ensure that the function exits properly.
Example
:Display SET /A index=2 echo The value of index is %index% EXIT /B 0
Conclusion
Command interpreter CMD. EXE has been around for a long time, but despite the lack of development, it remains a popular tool for automating routine actions in the Microsoft Windows operating system.