Batch files allow running multiple commands with a single command by automating repetitive tasks. They are simple text files with .bat or .cmd extensions containing commands that execute sequentially. The SET command in batch files allows defining, displaying, and removing environment variables as well as performing arithmetic operations. User input can be obtained using SET /P to prompt the user and assign the input to a variable. Batch files improve efficiency by reducing typing, automating complex tasks, and allowing conditional branching with GOTO.
2. Batch files
• Simple text files containing a series of commands that get
executed in sequence.
• The most common uses are to start programs and to run
utilities.
• Batch files do that with one command instead of the
multiple commands usually required.
3. The main advantages to using Batch Files
• Fewer keystrokes required to perform computer operations
Less chance of making typing errors.
• Short commands are easier to remember than a long series
of keystrokes.
• One command executes an extended chain of complicated
operations.
• Major time savings
4. Batch files
• These files have the special extension .bat or .cmd
• In Windows XP the command interpreter is the file cmd.exe.
5. Constructing & Running a batch file
• Constructing a batch file consists of nothing more
than opening any text editor like the accessory
Notepad, entering some lines containing commands,
and saving the file with an extension .bat
• Windows Wordpad, and a most of independent
editors like Wordstar, WordPerfect and MS_Word also
have the capability as long as you save the document
in ASCII (plain text).
6. Constructing & Running a batch file
Batch files can be run by:
clicking on it.
in a command prompt or the Start-Run line.
The first line in a batch file often consists of this command
@echo off
By default, a batch file will display its commands as it runs.
The purpose of this first command is to turn off this display.
The "at" sign "@" in front makes the command apply to itself
as well.
7. Example
• Our first batch file example is going to list all the files in a
folder and put the list in a new text file .
@echo off
dir "C:Program Files" > D:list.txt
Save this two-line file as myfile.bat to some convenient
location.
e.g.
@echo off
dir /s "C:Program Files" > D:list.txt
8. Important points
• Complete paths are used for files including the drive
letter.
• Also note the quotes around "C:Program Files".
Paths must be quoted whenever a file or folder name
has a space in it.
• The redirection symbol ">" that is used to send the
output to a file instead of the screen (standard
output).
9. Batch files can use arguments or data that is input from
the user. The process makes use of placeholders of the
form %1, %2,… These are replaced in the script by our
input data.
e.g.
dir %1 > %2
This type of situation cannot be clicked directly but
should be run in a command prompt.
A more general version with arguments
10. e.g.
@echo off
dir %1 > %2
Enter in Notepad and save as "makelist.bat".
To run the file, open a command prompt and enter:
C:>makelist D: D:list.txt
Where D: represent %1
and D:list.txt represent %2
If you want a list of all the subfolders as well, use the command
dir /s %1 > %2
11. If you want a list that only includes files of a certain
type, MP3 files for example, use
dir %1*.mp3 > %2
The line above illustrates the use of the wildcard "*".
The ability to use wildcards greatly enhances the
power of batch files.
12. it is easy to create batch files for some typical maintenance. To
create a very simple backup script, use xcopy. The code might be
:
xcopy %1 %2 /s
This will update all files in the input source folder %1 and its
subfolders by copying to the backup folder %2.
To copy all the files and subdirectories (including any empty
subdirectories) from drive C to drive D, type:
xcopy C: D: /s /e
More examples
13. To include any system or hidden files in the previous example, add
the /h command-line option as follows:
xcopy C: D: /s /e /h
To update files in the D:Reports directory with the files in the
D:Rawdata directory that have changed since December 29, 1993,
type:
xcopy D:rawdata D:reports /d:12-29-2003
Copy %1 %2 for copying file only
Again following of the command "del", a file to delete all temporary
files with extension TMP might contain :
del %1*.tmp
14. The "goto" command
• Generally, the execution of a batch file proceeds line-by-line with the
commands on each line being run in turn. However, it is often desirable
to execute a particular section of a batch file while skipping over other
parts. The capability to hop to a particular section is provided by the
"goto“ command.
• The target section is labeled with a line at the beginning that has a name
with a leading colon. Thus the script looks like
goto :label
...some commands
:label
...some other commands
• Execution will skip over "some commands" and start with "some other
commands".
• The label can be a line anywhere in the script, including before the
"goto" command.
15. e.g.
@echo off
Rem COPYIT.BAT transfers all files in all subdirectories of
Rem the source drive or directory (%1)
Rem the destination drive or directory (%2)
xcopy %1 %2 /s /e
if errorlevel 4 goto :lowmemory
if errorlevel 2 goto :abort
if errorlevel 0 goto :exit
:lowmemory
echo Insufficient memory to copy files or
echo invalid drive or command-line syntax.
goto :exit
:abort
echo You pressed CTRL+C to end the xcopy operation.
:exit
16. A more precise method of checking Errorlevels is to use the
%ERRORLEVEL% variable:
IF %ERRORLEVEL% GTR 0 Echo An error was found
IF %ERRORLEVEL% LSS 0 Echo An error was found
IF %ERRORLEVEL% EQU 0 Echo No error found
IF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE
(Echo An error was found)
17. Twin colons ::
• DOS will not execute any batch file line with twin
colons in front of it, nor display it on the monitor
screen. After seeing the second colon, DOS ignores
anything following and goes to the next line.
:: test1.bat
::
@echo off
…
18. The Rem statement
• For batch files of any complexity, comments are a good idea.
• Very often batch files contain lines that start with "Rem". which is
short for "Remark". This is a way to enter comments and
documentation.
• DOS does not execute these lines either, but it does read them.
• Using too many can slow down execution of a script.
19. SET : Display, set, or remove CMD environment variables. Changes made
with SET will remain only for the duration of the current CMD session.
Syntax
SET variable
SET variable=string
SET "
SET /A "variable=expression"
SET "variable="
SET /P variable=[promptString]
Key
variable : A new or existing environment variable name e.g. num
string : A text string to assign to the variable.
expression : Arithmetic expression
21. SET variable
c:>Set p
Type SET with a variable name to display that variable
c:>SET windir
Will display windir=c:windows
22. Variable names are not case-sensitve
SET variable=string
e.g.
@echo off
set xx=Ahmed
echo xx = %xx%
Pause
e.g.
@echo off
set xx=12
echo xx=%xx%
pause
23. C:> SET dept=Sales and Marketing
C:>set dd=20
C:> set d dept=Sales and Marketing
dd=20
For special characters like & you can surround the entire
expression with quotation marks.
SET dept=“Sales & Marketing”
One variable can be based on another, but this is not dynamic
E.g.
C:> set xx=fish
C:> set msg=%xx% chips
C:> set msg
msg=fish chips
C:> set xx=sausage
C:> set msg
msg=fish chips
26. Arithmetic expressions (SET /a)
SET /A will treat any character string in the expression as an environment variable
name. set num=6
+ Add set /a num=num+5
11
+= Add variable set /a num+=5
- Subtract (or unary) set /a num=num-5
-= Subtract variable set /a num-=5
* Multiply set /a num=num*5
*= Multiply variable set /a num*=5
/ Divide set /a num=num/5
/= Divide variable set /a num/=5
% Modulus set /a num=5%2
27. ~ One's complement (bitwise negation) set /a num=~5
& AND set /a num=5&3 0101 AND 0011 = 0001 (decimal 1)
&= AND variable set /a num&=3
| OR set /a num=5|3 0101 OR 0011 = 0111 (decimal 7)
|= OR variable set /a num|=3
^ XOR set /a num=5^3 0101 XOR 0011 = 0110 (decimal 6)
^= XOR variable set /a num^=3
<< Left Shift. (sign bit ⇨ 0)
>> Right Shift. //Neither ShiftRight nor ShiftLeft will detect overflow.
<<= Left Shift variable set /a num<<=2
>>= Right Shift variable set /a num>>=2
( ) Parenthesis group expressions set /a num=(2+3)*5
28. e.g.
@echo off
Set m1=13
Set m3=%m1%
Echo %m3%
Pause
e.g.
@echo off
Set a=10
Set /a a+=7
Set /a a-=3
Set /a a*=2
Set /a a/=7
echo %a%
pause
29. Examples:
SET /A result=2+4 while set result=2+4
6 echo %result%
2+4
SET /A result=5
5
SET /A result+=5
10
SET /A result=2<<3
16 { 2 Lsh 3 = binary 10 Lsh 3 = binary 10000 = decimal 16 }
SET /A result=5%2
1 { 5/2 = 2 + 2 remainder 1 = 1 }
SET /A var1=var2=var3=10
10
SET /A result=5 + var1
15
30. Multiple calculations can be performed in one line, by separating each calculation with commas, for
example:
set year=1999
set /a century=year/100, next=century+1
echo %century%
echo %next%
Leading Zero will specify Octal
Numeric values are decimal numbers, unless prefixed by
0x for hexadecimal numbers,
0 for octal numbers.
So
set /a ss=0x10
16
Because 0x10 = 020 = 16 decimal
The octal notation can be confusing - all numeric values that start with zeros are treated as octal
but 08 and 09 are not valid octal digits.
For example SET /a month=07 will return the value 7, but SET /a month=09 will return an error.
31. Variables from user input
• The set command can accept input from a user as the value for a
variable. The switch "/p" is used for this purpose. The syntax:
set /p variable = [string]
• “variable" is the name of the variable that will be assigned to the data
that you want the user to input.
• “string" is the message that the user will see as a prompt. If desired,
"string" can be omitted.
• When the user has entered the value, the script will continue. A message
string to prompt for input can be used. Example:
set /p xx = “Enter value”
32. e.g.
@echo off
Set /P dept=Please enter Department || Set dept=NothingChosen
If %dept%==NothingChosen goto :sub_error
If /i %dept%==finance goto :sub_finance
If /i %dept%==hr goto :sub_hr
goto :eof
:sub_finance
echo You chose the finance dept
goto :end
:sub_hr
echo You chose the hr dept
goto:end
:sub_error
echo Nothing was chosen
:end
pause
The Prompt string can be empty.
If the user does not enter anything (just presses return) then the variable will be
unchanged and an errorlevel (=1) will be set.
33. Example: Batch Calculator
@echo off
:: System Programing
title Batch Calculator
color 2e
:top
echo -------------------------------------------------
echo Welcome to Batch Calculator, Write an expression:
echo -------------------------------------------------
set /p expr=
set /a ans=%expr%
echo %expr%=%ans%
pause
cls
goto :top
34. Delete a variable
Type SET with just the variable name and an equals sign:
SET department=
Better still, to be sure there is no trailing space after the
= place the expression in parentheses or quotes:
(SET department=)
or
SET "department=“
SET is an internal command.
35. Permanent Setting environment variables
• To make permanent changes, use SETX.
• SETX extends the SET command so that permanent changes
in the environment variables can be made.
• In Microsoft Windows, environment variables defaults are stored in
the windows registry.
Example:
To add a folder C:New Folder to the path, the command would
be:
setx path “%PATH%;C:New Folder”
Echo %PATH%
• Because SETX writes variables to the master environment in
the registry, edits will only take effect when a new command
window is opened - they do not affect the current CMD.
35
36. If the variable name is not found in the current environment then
SET will set %ERRORLEVEL% to 1 .
This can be detected using IF ERRORLEVEL ...
If %ERRORLEVEL% ==1 (echo error found) else (echo no error
found)
37. e.g.
@echo off
D:
md YY
echo first msg > D:YYh1.txt
REM h1.txt will be created
echo second msg >> D:YYh1.txt
echo %date% >> D:YYh1.txt
echo %time% >> D:YYh1.txt
type D:YYh1.txt
Pause
Where >> is the APPEND operation
38. Divide operation
@echo off
Set /p x=enter the first number
Set /p y=enter the second number
set /a q=%x%*1000/%y%
echo q = %q:~0,-3%.%q:~-3%
pause
39. • The actual syntax is :
If condition (command1) Else (command2)
The "Else" part is optional.
e.g:
@echo off
set xx=11
set yy=22
if %xx% GTR %yy% (echo %xx%) else (echo %yy%)
Pause
e.g:
@echo off
set xx=%1
set yy=%2
if %xx% LSS %yy% (echo %xx% is less than %yy%) else (echo %xx% is
greater than or equal %yy%)
pause
40. For more general comparisons, use the operators in the
following table . (The operators are given in upper case in the
table but they are not case-dependent.)
Operator Meaning
EQU equal to
NEQ not equal to
LSS less than
LEQ
less than or
equal to
GTR greater than
GEQ
greater than or
equal to
Comparison operators
41. Rem Echo YPU number of times entered by user
@echo off
Set n=%1
Set i=0
:loop
echo YPU
Set /a i+=1
if %i% NEQ %n% goto :loop
pause
42. e.g.
cls
@echo off
set /p xx=Enter the first no.
set /p yy=Enter the second no.
if %xx% == %yy% (set /a xx +=20) else (set /a yy +=30)
echo %xx%
echo %yy%
Pause
e.g.
@echo off
set xx=GAC
set yy=BAC
if %xx% GTR %yy% (echo %xx% is greater than %yy%) else
(echo %xx% is not greater than %yy%)
pause
43. For case independence, use the switch "/i".
if /i string1 Operator string2 some_command
@echo off
set xx=Abc
set yy=abc
if /i %xx% == %yy% (echo %xx% is equal to %yy%) else (echo %xx% is
not equal to %yy%)
pause
e.g.
set xx=Abc
set yy=abc
if %xx% == %yy% (echo %xx%) else (echo %yy%+10)
44. If exist statement
There is a special "If exist" statement that can be used to test for
the existence of a file, followed by a command. An example would
be:
@ECHO OFF
SET /P answer=Enter filename to delete:
IF EXIST %answer% ( DEL /P %answer%)
ELSE ( ECHO ERROR: %answer% is not found)
Pause
You can also use a negative existence test:
if not exist somefile.ext echo no file
45. e.g.
@ECHO OFF
:prompt
SET /P answer=Enter filename to delete (q to quit):
IF /i "%answer%"=="q" GOTO :EOF
IF EXIST %answer% ( DEL /P %answer%) else (ECHO
ERROR: Incorrect entry!)
pause
cls
GOTO :prompt
46. "Goto" commands often occur in "if" statements.
e.g.
Set /p x=Enter integer value
if %x% GTR 10 goto :lab1
echo %x% is less than or equal 10
pause
Goto :eof
:lab1
echo %x% is greater than 10
pause
47. @echo off
set counter=0
if exist d:count.txt (del d:count.txt )
:numbers
if %counter% ==100 (goto :eof) else (echo %counter% >>
D:count.txt)
set /a counter+=1
goto :numbers
pause
48. Iterating with "For"
for {each item} in {a collection of items} do {command}
e.g.
@echo off
for /L %%X in (1,2,99) do (echo %%X >> D:count.txt)
Where L means List
for %%X in (1,2,99) do (echo %%X >> D:count.txt)
e.g.
@echo off
for /L %%X in (99,-1,1) do (echo %%X >> D:count.txt)
for %%F IN (*.docx) DO echo %%F
52. ASSOC
Manage file type and extension associations with the "assoc"
command. the syntax is
assoc [.ext[=[file Type]]]
ASSOC
ASSOC .ext
ASSOC .ext =
ASSOC .ext = file Type
More than one file extension can be associated with the same File Type.
e.g. both the extension .JPG and the extension .JPEG can be associated
with the File Type "jpegfile"
53. ASSOC without any parameters will get a list of what file types correspond to
the extensions currently registered on the system.
C:>assoc
54. The list can be quite long so it is best to redirect to a file or to pipe to the "more"
command
C:>assoc > list.txt
C:>assoc | more
If the only parameter is a file extension (including the leading period), the file type for
that extension will be given.
For example, to see what file type is associated with .txt , enter
assoc .txt
the output would normally be :
.txt=txtfile
55. As an example, to associate the extension .log with type txtfile,
enter
assoc .log=txtfile
To delete the association for a file type
ASSOC .ext=
Ex. assoc .log=
Using the ASSOC command will edit values stored in the registry
at HKey_Classes_Root.<file extension>
56. Repair .REG and .EXE file associations:
ASSOC .EXE=exefile
ASSOC .REG=regfile
ASSOC is an internal command.
•Also note that it is possible to create your own file extensions
and to associate them with a file type.
e.g.
assoc .kkk=txtfile
57. FTYPE
Manage file type and program associations with the "ftype"
command in particular, all active file types have an action named
"Open" that is the default action.
This is the action that is invoked when you double-click a file with
an extension associated with the file type.
There may also be other actions (listed in the Context Menu) but
ftype deals with "Open".
The syntax for ftype is
ftype [fileType[=[openCommandString]]]
58. Entering the bare command "ftype" will list all of the current file types that
have the open command strings defined and the corresponding command
string.
C:>ftype
It can be quite a long list so it is best to redirect to a file or to pipe to the
"more" command.
ftype | more
59. Using the text file type as an example, you would enter
ftype txtfile
This would produce the output :
txtfile=%SystemRoot%system32NOTEPAD.EXE %1
This shows that the executable file that opens text files is
notepad.exe located in the folder Windowssystem32 (The
environment variable %SystemRoot% is used to indicate the
Windows folder.)
C:>Echo %SystemRoot% will display
C:windows
60. Note the presence of the placeholder %1. This is necessary
because the full command for the open action requires the name of
the file that is to be opened and the placeholder stands for the file
name.
If it were desired to change the openCommandString to use
Wordpad instead of Notepad, the command (on one of my
computers) would be : ftype txtfile=“C:Program FilesWindows
NTAccessorieswordpad.exe" "%1"
(The path for WordPad will vary from one computer to the next.
This example is for illustration only).
Note the use of quotation marks to enclose a path with spaces in it.
61. ATTRIB
Display or change file attributes.
Syntax
ATTRIB [ + attribute | - attribute ] [pathname] [/S]
Key
+ : Turn an attribute ON
- : Clear an attribute OFF
pathname : Drive and/or filename e.g. C:*.txt
/S : Search the pathname including all subfolders.
62. attributes:
R Read-only
A Archive
S System
H Hidden
D:>attrib
will return the current attribute settings for the files in the
current directory.
C:>attrib /S
will return the current attribute settings for the current
directory and all its subdirectories.
63. Hidden and System attributes take priority
If a file has both the Hidden and System attributes set, you can clear both
attributes only with a single ATTRIB command.
For example, to clear the Hidden and System attributes for the
RECORD.TXT file, you would type:
ATTRIB -S -H RECORD.TXT
64. File Attributes
You can use wildcards (*) with the filename parameter to display
or change the attributes for a group of files.
e.g.
D:>attrib +r *.rar
Directory Attributes
You can display or change the attributes for a directory/folder. To
use ATTRIB with a directory, you must explicitly specify the
directory name;
you cannot use wildcards to work with directories.
For example, to hide the directory C:SECRET, you would type
the following:
C:>ATTRIB +H C:SECRET
To make the d:ypu directory not to read only:
D:>attrib -r ypu
65. COLOR
Sets the default console foreground and background colors.
Syntax: COLOR [background][foreground]
Color attributes are specified by 2 of the following hex digits. There should be
no space between the two color numbers.
Each digit can be any of the following values:
0 = Black
8 = Gray
1 = Blue
9 = Light Blue
2 = Green
A = Light Green
3 = Aqua
B = Light Aqua
4 = Red
C = Light Red
66. 5 = Purple
D = Light Purple
6 = Yellow
E = Light Yellow
7 = White
F = Bright White
If no argument is given, COLOR restores the color to what it was when
CMD.EXE started.
Errorlevels
If the color was successfully changed %ERRORLEVEL% = 0
If Background and foreground colors are the same (will fail)
%ERRORLEVEL% = 1
e.g. COLOR 00
COLOR is an internal command.
67. Comparing files
Syntax
COMP [pathname1] [pathname2] [/D] [/A] [/L] [/N=number] [/C]
Key
pathname1 The path and filename of the first file(s)
pathname2 The path and filename of the second file(s)
/D Display differences in decimal format. (default)
/A Display differences in ASCII characters.
/L Display line numbers for differences.
/N=number Compare only the first specified number of lines in each file.
/C do a case insensitive string comparison
Running COMP with no parameters will result in a prompt for the 2 files and
any options
To compare sets of files, use wildcards in pathname1 and pathname2
parameters.
68. To compare files of different sizes, use /N= to compare only the first n
lines (common portion of each file.)
Errorlevel
COMP will return an ErrorLevel as follows:
0 Files are identical
1 Files are different
2 Cannot open one of the files or invalid arguments or invalid
switch