Batch Script - Quick Guide
Batch Script - Quick Guide
Has control structures such as for, if, while, switch for better automating and scripting.
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.
Running a batch file is a simple matter of just clicking on it. Batch files can also be run in a
command prompt or the Start-Run line. In such case, the full path name must be used unless
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 1/56
5/20/23, 8:09 PM Batch Script - Quick Guide
the file's path is in the path environment. Following is a simple example of a Batch Script. This
Batch Script when run deletes all files in the current directory.
:: Deletes All files in the Current Directory With Prompts and Warnings
::(Hidden, System, and Read-Only Files are Not Affected)
:: @ECHO OFF
DEL . DR
Method 2 − Via the run command – The following snapshot shows to find the command
prompt(cmd.exe) on Windows server 2012.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 2/56
5/20/23, 8:09 PM Batch Script - Quick Guide
Once the cmd.exe is launched, you will be presented with the following screen. This will be
your environment for executing your batch scripts.
Environment Variables
In order to run batch files from the command prompt, you either need to go to the location to
where the batch file is stored or alternatively you can enter the file location in the path
environment variable. Thus assuming that the batch file is stored in the location
C:\Application\bin, you would need to follow these instructions for the PATH variable
inclusion.
OS Output
Windows Append the String; C:\Application\bin to the end of the system variable PATH.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 3/56
5/20/23, 8:09 PM Batch Script - Quick Guide
1 VER
This batch command shows the version of MS-DOS you are using.
2 ASSOC
This is a batch command that associates an extension with a file type (FTYPE),
displays existing associations, or deletes an association.
3 CD
This batch command helps in making changes to a different directory, or displays the
current directory.
4 CLS
5 COPY
This batch command is used for copying files from one location to the other.
6 DEL
7 DIR
8 DATE
9 ECHO
10 EXIT
11 MD
12 MOVE
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 4/56
5/20/23, 8:09 PM Batch Script - Quick Guide
13 PATH
14 PAUSE
This batch command prompts the user and waits for a line of input to be entered.
15 PROMPT
This batch command can be used to change or reset the cmd.exe prompt.
16 RD
This batch command removes directories, but the directories need to be empty before
they can be removed.
17 REN
18 REM
This batch command is used for remarks in batch files, preventing the content of the
remark from being executed.
19 START
20 TIME
21 TYPE
This batch command prints the content of a file or files to the output.
22 VOL
23 ATTRIB
24 CHKDSK
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 5/56
5/20/23, 8:09 PM Batch Script - Quick Guide
25 CHOICE
26 CMD
27 COMP
28 CONVERT
This batch command converts a volume from FAT16 or FAT32 file system to NTFS file
system.
29 DRIVERQUERY
This batch command shows all installed device drivers and their properties.
30 EXPAND
This batch command extracts files from compressed .cab cabinet files.
31 FIND
This batch command searches for a string in files or input, outputting matching lines.
32 FORMAT
This batch command formats a disk to use Windows-supported file system such as
FAT, FAT32 or NTFS, thereby overwriting the previous content of the disk.
33 HELP
34 IPCONFIG
35 LABEL
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 6/56
5/20/23, 8:09 PM Batch Script - Quick Guide
36 MORE
This batch command displays the contents of a file or files, one screen at a time.
37 NET
38 PING
This batch command sends ICMP/IP "echo" packets over the network to the
designated address.
39 SHUTDOWN
This batch command shuts down a computer, or logs off the current user.
40 SORT
This batch command takes the input from a source file and sorts its contents
alphabetically, from A to Z or Z to A. It prints the output on the console.
41 SUBST
This batch command assigns a drive letter to a local folder, displays current
assignments, or removes an assignment.
42 SYSTEMINFO
This batch command shows configuration of a computer and its operating system.
43 TASKKILL
44 TASKLIST
This batch command lists tasks, including task name and process id (PID).
45 XCOPY
This batch command copies files and directories in a more advanced way.
46 TREE
This batch command displays a tree of all subdirectories of the current directory to any
level of recursion or depth.
47 FC
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 7/56
5/20/23, 8:09 PM Batch Script - Quick Guide
This batch command lists the actual differences between two files.
48 DISKPART
This batch command shows and configures the properties of disk partitions.
49 TITLE
This batch command sets the title displayed in the console window.
50 SET
:: Deletes All files in the Current Directory With Prompts and Warnings
::(Hidden, System, and Read-Only Files are Not Affected)
::
@ECHO OFF
DEL .
DR
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.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 8/56
5/20/23, 8:09 PM Batch Script - Quick Guide
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 “”.
Step 3 − Write the name of the file as shown in the following image and press the Enter
button to execute the batch file.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 9/56
5/20/23, 8:09 PM Batch Script - Quick Guide
Step 3 − Right-click the file and choose the “Edit” option from the context menu. The file
will open in Notepad for further editing.
ECHO Command
@echo off
By default, a batch file will display its command as it runs. The purpose of this first command is
to turn off this display. The command "echo off" turns off the display for the whole script, except
for the "echo off" command itself. The "at" sign "@" in front makes the command apply to itself
as well.
Documentation
Very often batch files also contains lines that start with the "Rem" command. This is a way to
enter comments and documentation. The computer ignores anything on a line following Rem.
For batch files with increasing amount of complexity, this is often a good idea to have
comments.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 10/56
5/20/23, 8:09 PM Batch Script - Quick Guide
Uses the echo off command to ensure that the commands are not shown when the code is
executed.
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.
Finally, the echo command is used to tell the user that the operation is completed.
@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.
The following example shows a batch file which accepts 3 command line arguments and echo’s
them to the command line screen.
@echo off
echo %1
echo %2
echo %3
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 11/56
5/20/23, 8:09 PM Batch Script - Quick Guide
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
Following is a screenshot of how this would look in the command prompt when the batch file is
executed.
1
2
3
Example 1 2 3 4
The output would still remain the same as above. However, the fourth parameter would be
ignored.
Set Command
The other way in which variables can be initialized is via the ‘set’ command. Following is the
syntax of the set command.
Syntax
set /A variable-name=value
where,
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 12/56
5/20/23, 8:09 PM Batch Script - Quick Guide
The following example shows a simple way the set command can be used.
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
The above command produces the following output.
Hello World
The following code shows a simple way in which numeric values can be set with the /A switch.
@echo off
SET /A a = 5
SET /A b = 10
SET /A c = %a% + %b%
echo %c%
All of the arithmetic operators work in batch files. The following example shows arithmetic
operators can be used in batch files.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 13/56
5/20/23, 8:09 PM Batch Script - Quick Guide
@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
DOS scripting also has a definition for locally and globally scoped variables. By default,
variables are global to your entire command prompt session. Call the SETLOCAL command to
make variables local to the scope of your script. After calling SETLOCAL, any variable
assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of
file (EOF) in your script. The following example shows the difference when local and global
variables are set in the script.
Example
@echo off
set globalvar = 5
SETLOCAL
set var = 13145
set /A var = %var% + 5
echo %var%
echo %globalvar%
ENDLOCAL
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 14/56
5/20/23, 8:09 PM Batch Script - Quick Guide
The ‘globalvar’ is defined with a global scope and is available throughout the entire script.
The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’
and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’
statement is executed.
Output
The above command produces the following output.
13150
5
You will notice that the command echo %var% will not yield anything because after the
ENDLOCAL statement, the ‘var’ variable will no longer exist.
@echo off
echo %JAVA_HOME%
The output would show the JAVA_HOME directory which would depend from system to
system. Following is an example of an output.
C:\Atlassian\Bitbucket\4.0.1\jre
For example, consider the following piece of code which has no form of comments. If any
average person who has not developed the following script tries to understand the script, it
would take a lot of time for that person to understand what the script actually does.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 15/56
5/20/23, 8:09 PM Batch Script - Quick Guide
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 = %
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
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
Syntax
Rem Remarks
The following example shows a simple way the Rem command can be used.
Example
@echo off
Rem This program just displays Hello World
set message=Hello World
echo %message%
Output
The above command produces the following output. You will notice that the line with the Rem
statement will not be executed.
Hello World
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 16/56
5/20/23, 8:09 PM Batch Script - Quick Guide
Syntax
:: Remarks
The following example shows a simple way the Rem command can be used.
Example
@echo off
:: This program just displays Hello World
set message = Hello World
echo %message%
Output
The above command produces the following output. You will notice that the line with the ::
statement will not be executed.
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
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 17/56
5/20/23, 8:09 PM Batch Script - Quick Guide
You can now see that the code has become more understandable to users who have not
developed the code and hence is more maintainable.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 18/56
5/20/23, 8:09 PM Batch Script - Quick Guide
1 Create String
2 Empty String
Empty String
3 String Interpolation
String interpolation is a way to construct a new String value from a mix of constants,
variables, literals, and expressions by including their values inside a string literal.
4 String Concatenation
You can use the set operator to concatenate two strings or a string and a character, or
two characters. Following is a simple example which shows how to use string
concatenation.
5 String length
In DOS scripting, there is no length function defined for finding the length of a string.
There are custom-defined functions which can be used for the same. Following is an
example of a custom-defined function for seeing the length of a string.
6 toInt
A variable which has been set as string using the set variable can be converted to an
integer using the /A switch which is using the set variable. The following example
shows how this can be accomplished.
7 Align Right
This used to align text to the right, which is normally used to improve readability of
number columns.
8 Left String
9 Mid String
This is used to extract a substring via the position of the characters in the string.
10 Remove
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 19/56
5/20/23, 8:09 PM Batch Script - Quick Guide
The string substitution feature can also be used to remove a substring from another
string.
This is used to remove the first and the last character of a string.
13 Replace a String
To replace a substring with another string use the string substitution feature.
14 Right String
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 an Array
An array is created by using the following set command.
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.
Another way to implement arrays is to define a list of values and iterate through the list of
values. The following example show how this can be implemented.
Example
@echo off
set list = 1 2 3 4
(for %%a in (%list%) do (
echo %%a
))
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 20/56
5/20/23, 8:09 PM Batch Script - Quick Guide
Output
The above command produces the following output.
1
2
3
4
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]%
In this example, the index starts from 0 which means the first element can be accessed using
index as 0, the second element can be accessed using index as 1 and so on. Let's check the
following example to create, initialize and access arrays −
@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]%
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.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 21/56
5/20/23, 8:09 PM Batch Script - Quick Guide
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]%
You can modify an existing element of an Array by assigning a new value at a given index as
shown in the following example −
@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]%
@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
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 22/56
5/20/23, 8:09 PM Batch Script - Quick Guide
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
The above command produces the following 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
Output The above command produces the following output.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 23/56
5/20/23, 8:09 PM Batch Script - Quick Guide
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
The following key things need to be noted about the above code.
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.
We are able to access each element of the structure using the obj[%i%] notation.
Output
The above command produces the following output.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 24/56
5/20/23, 8:09 PM Batch Script - Quick Guide
Name = Joe
Value = 1
Name = Mark
Value = 2
Name = Mohan
Value = 3
1 If Statement
2 If/else Statement
The next decision making statement is the If/else statement. Following is the general
form of this statement.
3 Nested If Statements
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Bitwise operators
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 25/56
5/20/23, 8:09 PM Batch Script - Quick Guide
Arithmetic Operators
Batch script language supports the normal Arithmetic operators as any language. Following are
the Arithmetic operators available.
Show Example
Relational Operators
Relational operators allow of the comparison of objects. Below are the relational operators
available.
Show Example
EQU Tests the equality between two objects 2 EQU 2 will give true
NEQ Tests the difference between two objects 3 NEQ 2 will give true
LSS Checks to see if the left object is less than the right 2 LSS 3 will give true
operand
LEQ Checks to see if the left object is less than or equal to the 2 LEQ 3 will give true
right operand
GTR Checks to see if the left object is greater than the right 3 GTR 2 will give true
operand
GEQ Checks to see if the left object is greater than or equal to 3 GEQ 2 will give true
the right operand
Logical Operators
Logical operators are used to evaluate Boolean expressions. Following are the logical operators
available.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 26/56
5/20/23, 8:09 PM Batch Script - Quick Guide
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.
Show Example
Operator Description
Assignment Operators
Batch Script language also provides assignment operators. Following are the assignment
operators available.
Show Example
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 27/56
5/20/23, 8:09 PM Batch Script - Quick Guide
Output will be 8
Output will be 2
Output will be 15
Output will be 2
Output will be 2
Bitwise Operators
Bitwise operators are also possible in batch script. Following are the operators available.
Show Example
Operator Description
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 28/56
5/20/23, 8:09 PM Batch Script - Quick Guide
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
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
TIME
This command sets or displays the time.
Syntax
TIME
Example
@echo off
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 29/56
5/20/23, 8:09 PM Batch Script - Quick Guide
echo %TIME%
Output
The current system time will be displayed. For example,
22:06:52.87
Following are some implementations which can be used to get the date and time in different
formats.
Output
The above command produces the following output.
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.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 30/56
5/20/23, 8:09 PM Batch Script - Quick Guide
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.
One can even combine the stdout and stderr streams using the file number and the ‘&’ prefix.
Following is an example.
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.
The following example shows how you can redirect the output to a file called lists.txt. After you
execute the below command, the command prompt will take all the input entered by user till it
gets an EOF character. Later, it sends all the input to the file lists.txt.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 31/56
5/20/23, 8:09 PM Batch Script - Quick Guide
2 The system cannot find the file specified. Indicates that the file cannot be found in
specified location.
3 The system cannot find the path specified. Indicates that the specified path
cannot be found.
5 Access is denied. Indicates that user has no access right to specified resource.
-1073741801
-1073741510
The application failed to initialize properly. Indicates that the application has been
3221225794
launched on a Desktop to which the current user has no access rights. Another
0xC0000142 possible cause is that either gdi32.dll or user32.dll has failed to initialize.
-1073741502
Error Level
The environmental variable %ERRORLEVEL% contains the return code of the last executed
program or script.
By default, the way to check for the ERRORLEVEL is via the following code.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 32/56
5/20/23, 8:09 PM Batch Script - Quick Guide
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 < exitcodes > 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
Let’s assume we have a batch file called Find.cmd which has the following code. In the code, we
have clearly mentioned that we if don’t find the file called lists.txt then we should set the
errorlevel to 7. Similarly, if we see that the variable userprofile is not defined then we should
set the errorlevel code to 9.
Let’s assume we have another file called App.cmd that calls Find.cmd first. Now, if the Find.cmd
returns an error wherein it sets the errorlevel to greater than 0 then it would exit the program.
In the following batch file, after calling the Find.cnd find, it actually checks to see if the
errorlevel is greater than 0.
Call Find.cmd
Output
In the above program, we can have the following scenarios as the output −
If the file c:\lists.txt does not exist, then nothing will be displayed in the console output.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 33/56
5/20/23, 8:09 PM Batch Script - Quick Guide
If the variable userprofile 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.
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.
The "FOR" construct offers looping capabilities for batch files. Following is the
common construct of the ‘for’ statement for working with a list of values.
The ‘for’ statement also has the ability to move through a range of values. Following is
the general form of the statement.
Example
@ECHO OFF
:Loop
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 34/56
5/20/23, 8:09 PM Batch Script - Quick Guide
Output
Let’s assume that our above code is stored in a file called Test.bat. The above command will
produce the following output if the batch file passes the command line arguments of 1,2 and 3
as Test.bat 1 2 3.
1
2
3
The break statement is used to alter the flow of control inside loops within any
programming language. The break statement is normally used in looping constructs
and is used to cause immediate termination of the innermost enclosing loop.
As like any other languages, functions in Batch Script follows the same procedure −
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.
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.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 35/56
5/20/23, 8:09 PM Batch Script - Quick Guide
: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
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 36/56
5/20/23, 8:09 PM Batch Script - Quick Guide
1 Calling a Function
Functions can work with parameters by simply passing them when a call is made to
the function.
Functions can work with return values by simply passing variables names
Local variables in functions can be used to avoid name conflicts and keep variable
changes local to the function.
5 Recursive Functions
6 File I/O
In Batch Script, it is possible to perform the normal file I/O operations that would be
expected in any programming language.
7 Creating Files
The creation of a new file is done with the help of the redirection filter >. This filter can
be used to redirect any output to a file.
8 Writing to Files
Content writing to files is also done with the help of the redirection filter >. This filter
can be used to redirect any output to a file.
9 Appending to Files
Content writing to files is also done with the help of the double redirection filter >>.
This filter can be used to append any output to a file.
Reading of files in a batch script is done via using the FOR loop command to go
through each line which is defined in the file that needs to be read.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 37/56
5/20/23, 8:09 PM Batch Script - Quick Guide
11 Deleting Files
12 Renaming Files
For renaming files, Batch Script provides the REN or RENAME command.
13 Moving Files
The pipe operator (|) takes the output (by default, STDOUT) of one command and
directs it into the input (by default, STDIN) of another command.
When a batch file is run, it gives you the option to pass in command line parameters
which can then be read within the program for further processing.
One of the limitations of command line arguments is that it can accept only arguments
till %9. Let’s take an example of this limitation.
17 Folders
In Batch Script, it is possible to perform the normal folder based operations that would
be expected in any programming language.
18 Creating Folders
The creation of a folder is done with the assistance of the MD (Make directory)
command.
The listing of folder contents can be done with the dir command. This command
allows you to see the available files and directories in the current directory.
20 Deleting Folders
21 Renaming Folders
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 38/56
5/20/23, 8:09 PM Batch Script - Quick Guide
For renaming folders, Batch Script provides the REN or RENAME command.
22 Moving Folders
Syntax
TASKLIST [/S system [/U username [/P [password]]]] [/M [module] | /SVC | /V] [/FI filte
[/FO format] [/NH]
Examples
TASKLIST
The above command will get the list of all the processes running on your local system.
Following is a snapshot of the output which is rendered when the above command is run as it
is. As you can see from the following output, not only do you get the various processes running
on your system, you also get the memory usage of each process.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 39/56
5/20/23, 8:09 PM Batch Script - Quick Guide
The above command takes the output displayed by tasklist and saves it to the process.txt file.
The above command will only fetch those processes whose memory is greater than 40MB.
Following is a sample output that can be rendered.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 40/56
5/20/23, 8:09 PM Batch Script - Quick Guide
Syntax
TASKKILL [/S system [/U username [/P [password]]]] { [/FI filter]
[/PID processid | /IM imagename] } [/T] [/F]
Examples
taskkill /f /im notepad.exe
Syntax
START "title" [/D path] [options] "command" [parameters]
Wherein
Examples
START "Test Batch Script" /Min test.bat
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 41/56
5/20/23, 8:09 PM Batch Script - Quick Guide
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”.
The above command will actually run Microsoft word in another process and then open the file
TESTA.txt in MS Word.
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.
Creating an Alias
Alias are managed by using the doskey command.
Syntax
DOSKEY [options] [macroname=[text]]
Wherein
Following are the description of the options which can be presented to the DOSKEY command.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 42/56
5/20/23, 8:09 PM Batch Script - Quick Guide
1.
/REINSTALL
2.
/LISTSIZE = size
3.
/MACROS
4.
/MACROS:ALL
Displays all Doskey macros for all executables which have Doskey macros.
5.
/MACROS:exename
6.
/HISTORY
7.
/INSERT
8.
/OVERSTRIKE
9.
/EXENAME = exename
10.
/MACROFILE = filename
11.
macroname
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 43/56
5/20/23, 8:09 PM Batch Script - Quick Guide
12.
text
Example
Create a new file called keys.bat and enter the following commands in the file. The below
commands creates two aliases, one if for the cd command, which automatically goes to the
directory called test. And the other is for the dir command.
@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
The following screenshot shows that after the above created batch file is executed, you can
freely enter the ‘d’ command and it will give you the directory listing which means that your
alias has been created.
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
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 44/56
5/20/23, 8:09 PM Batch Script - Quick Guide
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.
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.
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.
Display driver and device info DevCon can display the following properties of drivers and
devices on local computers, and remote computers (running Windows XP and earlier) −
Hardware IDs, compatible IDs, and device instance IDs. These identifiers are described in
detail in device identification strings.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 45/56
5/20/23, 8:09 PM Batch Script - Quick Guide
Device status.
Search for devices DevCon can search for installed and uninstalled devices on a local or
remote computer by hardware ID, device instance ID, or device setup class.
Change device settings DevCon can change the status or configuration of Plug and Play
(PnP) devices on the local computer in the following ways −
Enable a device.
Disable a device.
Remove a device from the device tree and delete its device stack.
Rescan for Plug and Play devices.
Add and delete third-party driver packages from the driver store.
DevCon (DevCon.exe) is included when you install the WDK, Visual Studio, and the Windows
SDK for desktop apps. DevCon.exe kit is available in the following locations when installed.
%WindowsSdkDir%\tools\x64\devcon.exe
%WindowsSdkDir%\tools\x86\devcon.exe
%WindowsSdkDir%\tools\arm\devcon.exe
Syntax
devcon [/m:\\computer] [/r] command [arguments]
wherein
/m:\\computer − Runs the command on the specified remote computer. The backslashes are
required.
/r − Conditional reboot. Reboots the system after completing an operation only if a reboot is
required to make a change effective.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 46/56
5/20/23, 8:09 PM Batch Script - Quick Guide
DevCon HwIDs
DevCon Classes
DevCon ListClass
DevCon DriverFiles
DevCon DriverNodes
DevCon Resources
DevCon Stack
DevCon Status
DevCon Dp_enum
To search for information about devices on the computer, use the following commands −
DevCon Find
DevCon FindAll
To manipulate the device or change its configuration, use the following commands −
DevCon Enable
DevCon Disable
DevCon Update
DevCon UpdateNI
DevCon Install
DevCon Remove
DevCon Rescan
DevCon Restart
DevCon Reboot
DevCon SetHwID
DevCon ClassFilter
DevCon Dp_add
DevCon Dp_delete
Examples
Following are some examples on how the DevCon command is used.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 47/56
5/20/23, 8:09 PM Batch Script - Quick Guide
The following command uses the DevCon DriverFiles operation to list the file names of drivers
that devices on the system use. The command uses the wildcard character (*) to indicate all
devices on the system. Because the output is extensive, the command uses the redirection
character (>) to redirect the output to a reference file, driverfiles.txt.
The following command uses the DevCon status operation to find the status of all devices on
the local computer. It then saves the status in the status.txt file for logging or later review. The
command uses the wildcard character (*) to represent all devices and the redirection character
(>) to redirect the output to the status.txt file.
The following command enables all printer devices on the computer by specifying the Printer
setup class in a DevCon Enable command. The command includes the /r parameter, which
reboots the system if it is necessary to make the enabling effective.
The following command uses the DevCon Install operation to install a keyboard device on the
local computer. The command includes the full path to the INF file for the device (keyboard.inf)
and a hardware ID (*PNP030b).
The following command will scan the computer for new devices.
devcon scan
The following command will rescan the computer for new devices.
devcon rescan
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
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 48/56
5/20/23, 8:09 PM Batch Script - Quick Guide
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.
Reading from the registry is done via the REG QUERY command.
Deleting from the registry is done via the REG DEL command.
Copying from the registry is done via the REG COPY command.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 49/56
5/20/23, 8:09 PM Batch Script - Quick Guide
1 NET ACCOUNTS
View the current password & logon restrictions for the computer.
2 NET CONFIG
3 NET COMPUTER
4 NET USER
5 NET STOP/START
6 NET STATISTICS
7 NET USE
Syntax
PRINT [/D:device] [[drive:][path]filename[...]]
Example
print c:\example.txt /c /d:lpt1
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 50/56
5/20/23, 8:09 PM Batch Script - Quick Guide
The above command will print the example.txt file to the parallel port lpt1.
Syntax
RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry [ options ] [ @commandfile ]
/F[file] − Location of an INF file that the INF file specified with /f may depend on.
/k − Print test page to specified printer, cannot be combined with command when installing
a printer.
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
Following are the ways in which you can debug the batch file.
Here is a simple example that displays even numbers based on the input given. The echo
command is used to display the result and also if the input is not given. Similarly, the echo
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 52/56
5/20/23, 8:09 PM Batch Script - Quick Guide
command can be used in place when you think that the error can happen. For example, if the
input given is a negative number, less than 2, etc.
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
Output
C:\>test.bat
10
2
4
6
8
10
22
Press any key to continue ...
In the example below, the batch script is paused as the input value is mandatory and not
provided.
Example
@echo off
if [%1] == [] (
echo input value not provided
goto stop
) else (
echo "Valid value"
)
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 53/56
5/20/23, 8:09 PM Batch Script - Quick Guide
:stop
pause
Output
C:\>test.bat
input value not provided
Press any key to continue..
The command given in the .bat file is wrong. Let us log the message and see what we get.
The file testerrors.txt will display the error messages as shown below:
Looking at the above file the developer can fix the program and execute again.
@echo off
PING google.com
if errorlevel 1 GOTO stop
:stop
echo Unable to connect to google.com
pause
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 54/56
5/20/23, 8:09 PM Batch Script - Quick Guide
testlog.txt
In case of failure, you will see the following logs inside testlog.txt.
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 . . .
Syntax
test.bat > testlog.txt 2> testerrors.txt
Example
Create a file called test.bat and enter the following command in the file.
The above command has an error because the option to the net statistics command is given in
the wrong way.
Output
If the command with the above test.bat file is run as
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 55/56
5/20/23, 8:09 PM Batch Script - Quick Guide
And you open the file testerrors.txt, you will see the following error.
NET STATISTICS
[WORKSTATION | SERVER]
If you open the file called testlog.txt, it will show you a log of what commands were executed.
https://www.tutorialspoint.com/batch_script/batch_script_quick_guide.htm 56/56