KEMBAR78
Batch Scriptingf Tutoial | PDF | Control Flow | Parameter (Computer Programming)
0% found this document useful (0 votes)
44 views71 pages

Batch Scriptingf Tutoial

Batch scripting involves creating simple text files with commands that can be executed in a Windows environment to automate tasks. Key features include user input handling, control structures, and support for functions and arrays, while common uses range from server setup to application deployment. The tutorial covers creation, execution, and various commands and techniques for effective batch scripting.

Uploaded by

thehsr484
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views71 pages

Batch Scriptingf Tutoial

Batch scripting involves creating simple text files with commands that can be executed in a Windows environment to automate tasks. Key features include user input handling, control structures, and support for functions and arrays, while common uses range from server setup to application deployment. The tutorial covers creation, execution, and various commands and techniques for effective batch scripting.

Uploaded by

thehsr484
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 71

1

Batch scripting tutorial


 What is batch scripting?
 Simple files which store commands that can be
executed in window environment using command
prompt in order to do some meaningful tasks are known
as batch scripts.

Some of the features of Batch Script are −


 Can read inputs from users so that it can be processed
further.
 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.
 It supports RegEX.

Some of the common uses of Batch Script are −


 Setting up servers for different purposes.
 Automation of various mundane tasks.
 Automating housekeeping activities such as deleting
unwanted files or log files.
 Automating the deployment of applications from one
environment to another.
 Installing various applications on the system in one go.
 Installing programs on various machines at once.
 Saving work – hours for the people.

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
2

Batch scripting tutorial


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 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.
3

Batch scripting tutorial


:: Deletes All files in the Current Directory With Prompts and Warnings
::(Hidden, System, and Read-Only Files are Not Affected)
:: @ECHO OFF
DEL . DR
Note : we can use notepad, notepad ++, or VS
code for edit our batch file.
 Creation and execution:

Creation:

Right click >go to new>text document>and give file name and save with .bat
extension.

Execution:

1. By double click.
2. By using CMD:

Go to directory where your file is available >type file_name.extension and


press enter.

Some commands:

 echo :
we can use echo for output the string.
Example: echo Hello world.

 pause:
for holding the output.
 exit /b:
when output has displayed, press any key
to exit from terminal.

 Rem or (::) :
For comments.
 dir:
4

Batch scripting tutorial


by using dir command we can create a
new text file by giving path and file name.

 @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.

@echo off

:: move second.bat .\move_file


echo "hello world..."
echo "Hariom singh rajput."
dir "A:\batch scripting tutorial" > my_file_1.txt
echo "Work done..."
pause

 echo. :
for line break or giving space between two
lines.

 cls:
for clear screen.

 %random% :
5

Batch scripting tutorial


For generate a random number.
Ex. echo %random% %random%
%random% %random% …

Variables:
a. Local variables:
 Defined boundary in which they can
accessed.

Example of local variable:

@echo off
SETLOCAL
SET /A local_variable = 90
SET /A local_variable = %local_variable% + 10
echo LV = %local_variable%
ENDLOCAL

b. Global variables:
 They do not have a defined boundary,
and they can be used anywhere in the
whole script.

Example of global variable:

@echo off
SET /A global_variable = 90
echo GV = %globle_variable%

1. Create variables by using


command line arguments:
@ echo off
echo %1
6

Batch scripting tutorial


echo %2
echo %3
echo %4

Input:
A:\batch scripting
tutorial>variable.bat 10 20 30 40

Output:
10 20 30 40

2. Creating variables by using


set command:
Syntax: set variable_name = value
Example-

rem by using set command


set A1=hariom singh rajput
set marks=90
echo Name %A1% and total marks: %marks%

output:
Name hariom singh rajput and total marks: 90

Taking input by user in variable:


7

Batch scripting tutorial


Example:
set /p var1=“Enter first number: ”
set /p var2=“Enter second number: ”

NOTE: /p is used for taking input by


user.

Program for addition of two


numbers:
@ echo off
set A1=hariom singh rajput
set /A first = 90
set /A second = 90
set /A add = %first% + %second%
echo "Addision is: " %add%
NOTE: /A is used for giving numeric values
with variable name.
8

Batch scripting tutorial


OUTPUT:
"Addision is: " 180
Program for copy and delete any file by using batch file:
REM program for copy a file

REM program for copy a file


Cd/
A:
cd c++ programming language tutorial
cd 1 c++ tutorial
cd 15 others

xcopy inverse_of_matrix.cpp "D:"

REM program for delete a file

cd/
D:
del inverse_of_matrix.cpp

Note: when ENABLEDELAYEDEXPANSION in turned on than We


use ! ! to print output otherwise we use % % .

Batch scripting calculator program

@echo off
:a
echo ________Calculator________
echo.
set /p expression= Enter expression to calculate:
set /a ans=%expression%
9

Batch scripting tutorial


echo.
echo = %ans%
echo
pause
cls
goto a
10

Batch scripting tutorial


String commands:

S. Strings & Description


No

1 Create String

A string can be created in DOS in the following way.

Example
@echo off
set message = Hello World
echo %message%

Output
The above command produces the following output.
Hello World

2 Empty String
An empty string can be created in DOS Scripting by assigning it no
value during it’s initialization as shown in the following example.
Set a=
To check for an existence of an empty string, you need to
encompass the variable name in square brackets and also
compare it against a value in square brackets as shown in the
following example.
[%a%]==[]
The following example shows how an empty string can be created
and how to check for the existence of an empty string.

Example
@echo off
SET a=
SET b=Hello
if [%a%]==[] echo "String A is empty"
if [%b%]==[] echo "String B is empty "
11

Batch scripting tutorial


Output
The above command produces the following output.
String A is empty
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.
In DOS scripting, the string interpolation can be done using the set
command and lining up the numeric defined variables or any other
literals in one line when using the set command.
The following example shows how a string interpolation can be
done with numeric values as well.

Example
@echo off
SET a = Hello
SET b = World
SET /A d = 50
SET c=%a% and %b% %d%
echo %c%

Output
The above command produces the following output.
Hello and World 50

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.

Example
@echo off
SET a = Hello
SET b = World
SET c=%a% and %b%
echo %c%
12

Batch scripting tutorial


Output
The above command produces the following output.
Hello and World

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.

Example
@echo off
set str = Hello World
call :strLen str strlen
echo String is %strlen% characters long
exit /b

:strLen
setlocal enabledelayedexpansion

:strLen_Loop
if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop
(endlocal & set %2=%len%)
goto :eof
A few key things to keep in mind about the above program are −
 The actual code which finds the length of string is defined in
the :strLen block.
 The length of the string is maintained in the variable len.

Output
The above command produces the following output.
11
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.
13

Batch scripting tutorial


Example
@echo off
set var = 13145
set /A var=%var% + 5
echo %var%

Output
The above command produces the following output.
13150

7 Align Right
This used to align text to the right, which is normally used to
improve readability of number columns.

Example
@echo off
set str=My name is Hariom Singh Rajput
echo %str%
set str = %str:~-19%
echo %str%
A few key things to note about the above program is −
 Spaces are added to the variable of y, in this case we are
adding 9 spaces to the variable of y.
 We are using the ~-4 option to say that we just want to show
the last 4 characters of the string y.

Output
My name is Hariom Singh Rajput
Hariom Singh Rajput

8 Left String
This is used to extract characters from the beginning of a string.

Example
set str=Helloworld
14

Batch scripting tutorial


echo.%str%
set str=%str:~0,5%
echo.%str%
The key thing to note about the above program is, ~0,5 is used to
specify the characters which needs to be displayed. In this case,
we are saying character 0 to 5 should be displayed.

Output
The above command produces the following output.
Helloworld
Hello
9 Mid String
This is used to extract a substring via the position of the
characters in the string.

Example
@echo off
set str = Helloworld
echo %str%

set str = %str:~5,10%


echo %str%
The key thing to note about the above program is, ~5,10 is used
to specify the characters which needs to be displayed. In this case,
we want character 5 to 10 should be displayed.

Output
The above command produces the following output.
Helloworld
world

10 Remove
The string substitution feature can also be used to remove a
substring from another string.

Example
@echo off
set str = Batch scripts is easy. It is really easy.
15

Batch scripting tutorial


echo %str%

set str = %str:is = %


echo %str%
The key thing to note about the above program is, the ‘is’ word is
being removed from the string using the :’stringtoberemoved’ =
command.

Output
The above command produces the following output.
Batch scripts is easy. It is really easy.
Batch scripts easy. It really easy.

11 Remove Both Ends


This is used to remove the first and the last character of a string.

Example
@echo off
set str = Batch scripts is easy. It is really easy
echo %str%

set str = %str:~1,-1%


echo %str%
The key thing to note about the above program is, the ~1,-1 is
used to remove the first and last character of a string.

Output
The above command produces the following output.
Batch scripts is easy. It is really easy
atch scripts is easy. It is really eas

12 Remove All Spaces


This is used to remove all spaces in a string via substitution.

Example
@echo off
set str = This string has a lot of spaces
16

Batch scripting tutorial


echo %str%

set str=%str:=%
echo %str%
The key thing to note about the above program is, the : = operator
is used to remove all spaces from a string.

Output
The above command produces the following output.
This string has a lot of spaces
Thisstringhasalotofspaces
13 Replace a String
To replace a substring with another string use the string
substitution feature.

Example
@echo off
set str=This message needs changed.
echo %str%

set str=%str:needs=has%
echo %str%
The key thing to note about the above program is, the example
replaces the word ‘needs’ with the string ‘has’ via the statement
%str:needs = has%

Output
The above command produces the following output.
This message needs changed.
This message has changed.
14 Right String
This is used to extract characters from the end of a string.

Example
@echo off
set str = This message needs changed.
echo %str%

set str = %str:~-8%


17

Batch scripting tutorial


echo %str%
The key thing to note about the above program is, the right hand
of the string is extracted by using the ~-‘number of characters to
extract’ operator.

Output
The above command produces the following output.
This message needs changed.
changed.

Making Decisions:
In order to make decisions whether one or more
conditions must be executed or not we use these
statements:
a) If-statement
b) If-else statement
c) Nested-if statements

Here is a flowchart to highlight the concept


of if else statement.
18

Batch scripting tutorial

A) If statement:
The if the statement is one of the selection statements. It
uses to select statements depending on the value of a
controlling expression.

Syntax: if(condition) do_some_work

Example:
@echo off

REM comparing numeric values

set /A a = 50

set /A b = 100
19

Batch scripting tutorial


set /A sum = %a% + %b%

if %sum%==150 echo The sum is 150

if %sum%==100 echo The sum is 100

REM comparing string values

set str1=hariom

set str2=rajput

if %str1%==hariom echo This is correct

if %str2%==hariom echo This is incorrect

B) If_else statements:
If condition returns true then the statements inside the
body of “if” are executed and the statements inside body
of “else” are skipped.
If condition returns false then the statements inside the
body of “if” are skipped and the statements in “else” are
executed.

Syntax: if(condition)
(do_something)
ELSE
(do_something_else)

Example:
@echo off

set str1=hariom

set str2=string2

if %str1%==hariom (
20

Batch scripting tutorial


echo "The value of variable is string1"

) else (

echo "Unknown value"

if %str2%==string3 (

echo "This is correct value"

) else (

echo "This is incorrect value"

C) Nested if statement:
Sometimes, there is a requirement to have multiple “if”
statement embedded inside each other. Following is the
general form of this statement:
Syntax: if(condition1) if(condition2) do_something
Thus, only if condition1 and condition2 are met, will the
code in the do_something block be executed

Example:
@echo off

set /A first = 50

set /A second = 100

if %first%==50 if %second%==100 echo "Both values are


correct"
21

Batch scripting tutorial


goto statement:
the capability to hop to a particular section is
provided by the appropriately named “go to” command.
Syntax: ……..
goto :label
…..some commands to run
:label
……some other commands to run

Example:
@echo off

set /A a = 100

if %a%==50 goto :labelone

if %a%==100 goto :labeltwo

:labelone

echo The value of a is 50

exit /b 0

:labeltwo

echo The value of a is 100

Operators:
An operator is a symbol that tells the compiler to
perform specific mathematical or logical manipulations.
22

Batch scripting tutorial


In batch script, the following types of operators are
possible.
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
 Bitwise operators

ARITHMETIC OPERATORS
Batch script language supports the normal Arithmetic
operators as any language. Following are the
Arithmetic operators available.

Example
Oper Description Example
ator

+ Addition of two operands 1 + 2 will


give 3

− Subtracts second operand from the 2 − 1 will


first give 1

* Multiplication of both operands 2 * 2 will


give 4

/ Division of the numerator by the 3 / 2 will


denominator give 1.5
23

Batch scripting tutorial


% Modulus operator and remainder of 3 % 2 will
after an integer/float division give 1

Example:

@echo off

set /A first = 50

set /A second = 100

set /A third = 153

rem return addition

set /A sum = %first% + %second%

echo Sum = %sum%

rem return substraction

set /A sum = %first% - %second%

echo substraction = %sum%

rem return multiplication

set /A sum = %first% * %second%

echo multiplication = %sum%

rem return division

set /A sum = %second% / %first%

echo division = %sum%

rem return remainder

set /A sum = %third% %% %first%

echo remainder = %sum%

OUTPUT:

Sum = 150
24

Batch scripting tutorial


substraction = -50

multiplication = 5000

division = 2

remainder = 3

RELATIONAL OPERATORS
Relational operators allow of the comparison of
objects. Below are the relational operators available.

Example
Oper Description Example
ator

EQU Tests the equality between two 2 EQU 2 will


objects give true

NEQ Tests the difference between two 3 NEQ 2 will


objects give true

LSS Checks to see if the left object is 2 LSS 3 will


less than the right operand give true

LEQ Checks to see if the left object is 2 LEQ 3 will


less than or equal to the right give true
operand

GTR Checks to see if the left object is 3 GTR 2 will


greater than the right operand give true
25

Batch scripting tutorial


GEQ Checks to see if the left object is 3 GEQ 2 will
greater than or equal to the right give true
operand

@echo off

set /A first = 5

set /A second = 10

if %first% EQU %second% echo First is equal to second

if %first% neq %second% echo First is not equal to second

if %first% lss %second% echo First is less than second

if %first% leq %second% echo First is less than or equal to second

if %first% gtr %second% echo First is greater than second

if %first% geq %second% echo First is greater than or equal to second

OUTPUT:

First is not equal to second

First is less than second

First is less than or equal to second

LOGICAL OPERATORS
Logical operators are used to evaluate Boolean
expressions. Following are the logical operators
available.
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.
26

Batch scripting tutorial


Example
Operator Description

AND This is the logical “and” operator

OR This is the logical “or” operator

NOT This is the logical “not” operator

@echo off

SET /A a = 5

SET /A b = 10

IF %a% GEQ 10 (

IF %b% LEQ 0 (

ECHO %a% is NOT less than 10 OR %b% is NOT greater than 0

) ELSE (

ECHO %a% is less than 10 OR %b% is greater than 0

) ELSE (

ECHO %a% is less than 10 OR %b% is greater than 0

OUTPUT:

5 is less than 10 OR 10 is greater than 0


27

Batch scripting tutorial


ASSIGNMENT OPERATORS
Batch Script language also provides assignment
operators. Following are the assignment operators
available.

Example
Oper Description Exampl
ator e

This adds right operand to the left Set /A a


operand and assigns the result to left =5
+= operand a += 3
Output
will be 8

This subtracts the right operand from Set /A a


the left operand and assigns the result =5
to the left operand
-= a -= 3

Output
will be 2

This multiplies the right operand with Set /A a


the left operand and assigns the result =5
to the left operand
*= a *= 3

Output
will be 15

/= This divides the left operand with the Set /A a


right operand and assigns the result to =6
28

Batch scripting tutorial


the left operand a/ = 3

Output
will be 2

This takes modulus using two operands Set /A a


and assigns the result to the left =5
operand
%= a% = 3

Output
will be 2

@echo off

set /A number1 = 50

set /A number2 = 100

set /A number3 = 200

set /A number4 = 300

set /A number5 = 400

set /A number1+=50

echo %number1%

set /A number2-=50

echo %number2%

set /A number3*=50

echo %number3%

set /A number4/=50

echo %number4%

set /A number5%%=50

echo %number5%
29

Batch scripting tutorial


OUTPUT:

100

50

10000

BITWISE OPERATORS
Bitwise operators are also possible in batch script.
Following are the operators available.

Example
Operator Description

& This is the bitwise “and” operator

| This is the bitwise “or” operator

^ This is the bitwise “xor” or Exclusive or operator

@echo off

set /A "Result = 7 & 4"

echo %Result%

set /A "Result = 7 | 4"

echo %Result%
30

Batch scripting tutorial


set /A "Result = 7 ^ 4"

echo %Result%

OUTPUT:

Following is the truth table showcasing these


operators.

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

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.
31

Batch scripting tutorial


Following are the common exit code and their description.
Error Description
Code

0 Program successfully completed.

1 Incorrect function. Indicates that Action has


attempted to execute non-recognized command in
Windows command prompt cmd.exe.

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.

9009 Program is not recognized as an internal or


external command, operable program or batch
0x2331 file. Indicates that command, application name or
path has been misspelled when configuring the
Action.
221225 Not enough virtual memory is available.
495
It indicates that Windows has run out of memory.
0xC000
0017
-
107374
1801

322122 The application terminated as a result of a


5786 CTRL+C. Indicates that the application has been
terminated either by the user's keyboard input
0xC000 CTRL+C or CTRL+Break or closing command
013A prompt window.
-
107374
1510
32

Batch scripting tutorial


322122 The application failed to initialize properly.
5794 Indicates that the application has been launched
on a Desktop to which the current user has no
0xC000 access rights. Another possible cause is that either
0142 gdi32.dll or user32.dll has failed to initialize.
-
107374
1502

Loops:
Since BASH is a command-line language, we get some pretty
feature-rich experience to leverage the programming skills to
perform tasks in the terminal. We can use loops and
conditional statements in BASH scripts to perform some
repetitive and tricky problems in a simple programmatic way.

A loop executes the sequence of statements many times until


the stated condition becomes false. A loop consists of two
parts, a body of a loop and a control statements. the control
statement is a combination of some conditions that direct the
body of the loop to execute until the specified condition
becomes false. The purpose of the loop is to repeat the some
code a number of times.

Syntax
FOR /L %%variable IN (lowerlimit,Increment,Upperlimit) DO
do_something
Where
The /L switch is used to denote that the loop is used for
iterating through ranges.
Variable declaration – This step is executed only once for the
entire loop and used to declare any variables which will be
used within the loop. In Batch Script, the variable declaration is
done with the %% at the beginning of the variable name.
33

Batch scripting tutorial


The IN list contains of 3 values. The lowerlimit, the increment,
and the upperlimit. So, the loop would start with the lowerlimit
and move to the upperlimit value, iterating each time by the
Increment value.
The do_something code block is what needs to be executed for
each iteration.
Following is an example of how the looping through ranges can
be carried out.

Example
@ECHO OFF
FOR /L %%X IN (0,1,5) DO ECHO %%X

Output
The above program produces the following output.
0
1
2
3
4
5

Reverse for loop

Example

@ECHO OFF
echo print reverse odd number (10-1):
for /l %%a in (10,-2,1) do ( echo %%a )

echo Reverse natural number between 10-1 are:


for /l %%i in (10,-1,1) do ( echo %%i)

Output
34

Batch scripting tutorial


The above program produces the following output.
print reverse odd number (10-1):
10
8
6
4
2
Reverse natural number between 10-1 are:
10
9
8
7
6
5
4
3
2
1

ARRAYS:
Arrays are not specifically defined as a type in Batch Script but
can be implemented. The following things need to be noted
when arrays are implemented in Batch Script.

 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
35

Batch scripting tutorial


set list=1 2 3 4
(for %%a in (%list%) do (
echo %%a
))

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.
@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 above command produces the following output.
The first element of the array is 1
The second element of the array is 2
The third element of the array is 3

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]%
36

Batch scripting tutorial


The above command produces the following output.
The last element of the array is 4
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]%
The above command produces the following output.
The new value of the second element of the array is 5

Iterating Over an Array


Iterating over an array is achieved by using the ‘for’ loop and
going through each element of the array. The following
example shows a simple way that an array can be
implemented.
@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]!
)

Following things need to be noted about the above program −


 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
37

Batch scripting tutorial


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.
1
2
3
4
"The length of the array is" 4

Creating Structures in Arrays


Structures can also be implemented in batch files using a little
bit of an extra coding for implementation. The following
example shows how this can be achieved.

EXAMPLE
@echo off
set obj[0].Name=Joe
set obj[0].ID=1
set obj[1].Name=Mark
38

Batch scripting tutorial


set obj[1].ID=2
set obj[2].Name=Mohan
set obj[2].ID=3
FOR /L %%i IN (0 1 2) DO (
call echo Name = %%obj[%%i].Name%%
call echo Value = %%obj[%%i].ID%%
)

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.
Name=Joe
Value=1
Name=Mark
Value=2
Name=Mohan
Value=3

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.
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
39

Batch scripting tutorial


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.
Following is the syntax of a simple function.
: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.
Following is an example of a simple function.

EXAMPLE
:Display
SET /A index=2
echo The value of index is %index%
EXIT /B 0

Calling a Function
A function is called in Batch Script by using the call command.
Following is the syntax.

SYNTAX
call :function_name
Following example shows how a function can be called from the main
program.

EXAMPLE
@echo off
SETLOCAL
CALL :Display
EXIT /B %ERRORLEVEL%
:Display
40

Batch scripting tutorial


SET /A index=2
echo The value of index is %index%
EXIT /B 0

One key thing to note when defining the main program is to


ensure that the statement EXIT /B %ERRORLEVEL% is put in
the main program to separate the code of the main program
from the function.

OUTPUT
The above command produces the following output.
The value of index is 2

Functions with Parameters


Functions can work with parameters by simply passing them
when a call is made to the function.

SYNTAX
Call :function_name parameter1, parameter2… parametern
The parameters can then be accessed from within the function
by using the tilde (~) character along with the positional
number of the parameter.
Following example shows how a function can be called with parameters.

EXAMPLE
@echo off
SETLOCAL
CALL :Display 5 , 10
EXIT /B %ERRORLEVEL%
:Display
echo The value of parameter 1 is %~1
echo The value of parameter 2 is %~2
EXIT /B 0

As seen in the above example, ~1 is used to access the first


parameter sent to the function, similarly ~2 is used to access
the second parameter.

OUTPUT
The above command produces the following output.
The value of parameter 1 is 5
41

Batch scripting tutorial


The value of parameter 2 is 10

Functions with Return Values


Functions can work with return values by simply passing
variables names which will hold the return values when a call
is made to the function as shown below

SYNTAX
Call :function_name value1, value2… valuen
The return values are set in the function using the set
command and the tilde(~) character along with the positional
number of the parameter.
Following example shows how a function can be called with return
values.

EXAMPLE
@echo off
SETLOCAL
CALL :SetValue value1,value2
echo %value1%
echo %value2%
EXIT /B %ERRORLEVEL%
:SetValue
set "%~1 = 5"
set "%~2 = 10"
EXIT /B 0

OUTPUT
The above command produces the following output.
5
10

Local Variables in Functions


Local variables in functions can be used to avoid name
conflicts and keep variable changes local to the function. The
SETLOCAL command is first used to ensure the command
processor takes a backup of all environment variables. The
variables can be restored by calling ENDLOCAL command.
Changes made in between are local to the current batch script.
ENDLOCAL is automatically called when the end of the batch
file is reached, i.e. by calling GOTO:EOF.
42

Batch scripting tutorial


Localizing variables with SETLOCAL allows using variable
names within a function freely without worrying about name
conflicts with variables used outside the function.
Following example shows how local variables can be used in functions.

EXAMPLE
@echo off
set str = Outer
echo %str%
CALL :SetValue str
echo %str%
EXIT /B %ERRORLEVEL%
:SetValue
SETLOCAL
set str = Inner
set "%~1 = %str%"
ENDLOCAL
EXIT /B 0

OUTPUT
In the above program, the variable ‘str’ is being localized in
the function SetValue. Thus even though the str value is being
returned back to the main function, the value of str in the main
function will not be replaced by the value being returned from
the function.
The above command produces the following output.
Outer
Outer

Recursive Functions
The ability to completely encapsulate the body of a function by
keeping variable changes local to the function and invisible to
the caller. We can now have the ability to call a function
recursively making sure each level of recursion works with its
own set of variables even though variable names are being
reused.
Following example shows how recursive functions can be used.

EXAMPLE
The example shows how to calculate a Fibonacci number recursively.
43

Batch scripting tutorial


@echo off
set "fst = 0"
set "fib = 1"
set "limit = 1000000000"
call:myFibo fib,%fst%,%limit%
echo.The next Fibonacci number greater or equal %limit% is %fib%.
echo.&pause&goto:eof
:myFibo -- calculate recursively
:myFibo -- calculate recursively the next Fibonacci number greater or equal
to a limit
SETLOCAL
set /a "Number1 = %~1"
set /a "Number2 = %~2"
set /a "Limit = %~3"
set /a "NumberN = Number1 + Number2"

if /i %NumberN% LSS %Limit% call:myFibo NumberN,%Number1%,%Limit%


(ENDLOCAL
IF "%~1" NEQ "" SET "%~1 = %NumberN%"
)goto:eof

OUTPUT
The above command produces the following output.
The next Fibonacci number greater or equal 1000000000 is 1134903170.

Working with files and folders


Files:
A file is a collection of information which is recorded/saved in
our hard disks.

A) Creating files
B) Reading files
C) Writing to files
D) Deleting files
E) Renaming files

Folder:
A folder is a directory where you keep your content.
44

Batch scripting tutorial


A) Creating folders
B) Listing contents
C) Deleting folders
D) Renaming folders
E) Moving folders

Parameters
> Write to file.

>> Append to file.

Working with files:


1. Creating a file:
@echo off

echo "Hello! My name is Hariom Singh Rajput">"A:\batch scripting


tutorial\7 working with files and folders\New_file1.txt"

echo "Hi! My name is Hariom Singh Rajput and i am a computer


science student">"A:\batch scripting tutorial\7 working with files and
folders\New_file2.txt"

echo "Hello friends! Good morning">"A:\batch scripting tutorial\7


working with files and folders\New_file3.txt"

2. Write a file:
@echo off

rem clear old text and written new text


echo This is new text which is written by me. > My_file1.text

rem append text


echo hi, My name is hariom mewada >> My_file1.txt
echo my mobile number is : 9302765839 >> My_file1.txt

3. Delete a file:
45

Batch scripting tutorial


@echo off
rem delete only one file
del New_file.txt

rem delete all file of .txt extension


del *.txt

4. Reading a file:
@echo off
for /f "tokens=*" %%x in (New_file.txt) do ( echo %%x)

5. Rename a file:
@echo off
rename New_file1.txt My_file1.txt

Working with folders:


1. Create a folder:
@echo off
md Newfolder1
md Newfolder2
mkdir Newfolder3
mkdir Newfolder4
note: we can use md or mkdir for creating a folder or direcrory.

2. Rename a folder:
@echo off
ren Newfolder2 My_folder1

3. Move a folder:
@echo off
move Newfolder1 .\My_folder1
46

Batch scripting tutorial


4. Delete a folder:
@echo off
REM rd delete folder without asking again for conformation

REM del delete folder but it will ask "are you sure to
delete folder" and if you press y than it delete folder and if you press n
than it will not delete your folder

rd Newfolder1
del My_folder1
del Newfolder2
rd Newfolder3
rd Newfolder4

Process and logging


 Processes are the related activities inside a system that works together to do
something.
 A log file is a file that records either events that occur in an operating system or when
software runs, ore messages between different users of a communication software.
Logging is the act of keeping a log.

a) How to get the list.


b) How to log it in a text file.
c) Killing a process.
d) Starting a new process.

Example:
@echo off
REM To get the list of all the running processes
TASKLIST

REM Logging in a file


TASKLIST > processes.txt

REM Tell you the memory usage greater than a number


REM Here /fi displays a set of tasks that match a given criteria specified by the
filter
tasklist /fi "memusage gt 50000" > processesGT50000.txt

REM killing a process


rem syntax Taskkill /f /im name.exe
Taskkill /f /im notepad.exe
47

Batch scripting tutorial


REM starting a new process
rem syntax START "title" [/D path][options] " command" [parameters]
START notepad.exe "Notepadfile.txt"

Process:
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]

Example:
@echo off
REM To get the list of all the running processes
TASKLIST

Logging:
Logging in is possible in Batch Script by using the redirection
command.
Syntax
test.bat > testlog.txt 2> testerrors.txt

Example
@echo off
REM Logging in a file
TASKLIST > processes.txt

Output

Image Name PID Session Name Session# Mem Usage


========================= ========
================ =========== ============
System Idle Process 0 Services 0 8K
48

Batch scripting tutorial


System 4 Services 0 2,872 K
Registry 160 Services 0 80,376 K
smss.exe 596 Services 0 1,112 K
csrss.exe 952 Services 0 6,212 K
wininit.exe 408 Services 0 7,128 K
services.exe 872 Services 0 10,264 K
lsass.exe 876 Services 0 24,928 K
svchost.exe 1152 Services 0 38,088 K
fontdrvhost.exe 1184 Services 0 2,728 K
WUDFHost.exe 1240 Services 0 8,888 K
svchost.exe 1332 Services 0 16,848 K
svchost.exe 1372 Services 0 9,028 K
svchost.exe 1452 Services 0 9,136 K
svchost.exe 1460 Services 0 9,480 K
svchost.exe 1520 Services 0 11,300 K
svchost.exe 1540 Services 0 10,464 K
svchost.exe 1548 Services 0 8,156 K
IntelCpHDCPSvc.exe 1712 Services 0 5,280 K
svchost.exe 1760 Services 0 8,972 K
svchost.exe 1776 Services 0 8,600 K
svchost.exe 1860 Services 0 17,120 K
svchost.exe 1872 Services 0 5,568 K
svchost.exe 1888 Services 0 7,412 K
svchost.exe 2016 Services 0 5,992 K
svchost.exe 2032 Services 0 16,752 K
svchost.exe 2088 Services 0 9,412 K
svchost.exe 2160 Services 0 9,892 K
svchost.exe 2168 Services 0 19,460 K
igfxCUIServiceN.exe 2300 Services 0 10,396 K
svchost.exe 2368 Services 0 9,968 K
svchost.exe 2380 Services 0 9,296 K
svchost.exe 2532 Services 0 6,344 K
WUDFHost.exe 2688 Services 0 18,984 K
AppHelperCap.exe 2716 Services 0 17,248 K
DiagsCap.exe 2724 Services 0 9,220 K
NetworkCap.exe 2736 Services 0 25,960 K
SysInfoCap.exe 2812 Services 0 30,832 K
svchost.exe 2888 Services 0 22,516 K
TouchpointAnalyticsClient 3036 Services 0 89,912 K
svchost.exe 3064 Services 0 13,624 K
svchost.exe 2292 Services 0 7,912 K
svchost.exe 3336 Services 0 18,816 K
svchost.exe 3380 Services 0 19,744 K
svchost.exe 3424 Services 0 14,712 K
svchost.exe 3420 Services 0 5,488 K
mfemms.exe 3472 Services 0 16,780 K
svchost.exe 3496 Services 0 7,460 K
svchost.exe 3504 Services 0 8,412 K
Memory Compression 3528 Services 0 259,680 K
svchost.exe 3772 Services 0 53,488 K
MMSSHOST.exe 3812 Services 0 55,728 K
svchost.exe 3916 Services 0 6,384 K
svchost.exe 3928 Services 0 10,896 K
svchost.exe 3984 Services 0 19,808 K
49

Batch scripting tutorial


mfevtps.exe 4008 Services 0 13,844 K
svchost.exe 4072 Services 0 15,752 K
spoolsv.exe 3608 Services 0 13,672 K
ProtectedModuleHost.exe 4160 Services 0 15,788 K
svchost.exe 4188 Services 0 18,040 K
svchost.exe 4332 Services 0 7,492 K
wlanext.exe 4460 Services 0 6,080 K

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.

S.No Types of Registry & Description

1 Reading from the Registry

Reading from the registry is done via the REG QUERY command.

Example:

@echo off

reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlset\Control\

windows\
50

Batch scripting tutorial


2 Adding to the Registry

Adding to the registry is done via the REG ADD command.

Example:

@echo off

REG ADD HKEY_CURRENT_USER\Console /v TestData /d "This is an

entry"

REG QUERY HKEY_CURRENT_USER\Console /v TestData

3 Deleting from the Registry

Deleting from the registry is done via the REG DEL command.

Example:

@echo off

REG DELETE HKEY_CURRENT_USER\Console /v TestData /f

REG QUERY HKEY_CURRENT_USER\Console /v TestData

4 Copying Registry Keys

Copying from the registry is done via the REG COPY command.

Example:

@echo off

REG COPY HKEY_CURRENT_USER\Console HKEY_CURRENT_USER\

Console\TestData

REG QUERY HKEY_CURRENT_USER\Console\TestData

5 Comparing Registry Keys

Comparing registry keys is done via the REG COMPARE


command.
51

Batch scripting tutorial


Example:

@echo off

REG COMPARE HKEY_CURRENT_USER\Console HKEY_CURRENT_USER\

Console\TestData

Debugging
Debugging a batch script becomes important when you are
working on a big complex batch script.
Following are the ways in which you can debug the batch file.
Using echo command
A very simple debug option is to make use of echo command
in your batch script wherever possible. It will display the
message in the command prompt and help you debug where
things have gone wrong.
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
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
52

Batch scripting tutorial


Output
C:\>test.bat
10
2
4
6
8
10
22
Press any key to continue ...
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.

Example
@echo off
if [%1] == [] (
echo input value not provided
goto stop
) else (
echo "Valid value"
)
:stop
pause

Output
C:\>test.bat
input value not provided
Press any key to continue..

Batch scripting commands


S. Commands & Description
No

1 VER
53

Batch scripting tutorial


This batch command shows the version of MS-DOS you
are using.
Example
@echo off
ver

Output
Microsoft Windows [Version 6.3.9600]
2 ASSOC

This is a batch command that associates an extension


with a file type (FTYPE), displays existing associations,
or deletes an association.

Syntax
assoc – Displays all the file extensions
assoc | find “.ext” – Displays only those file extensions
which have the extension ext.
Example
@echo off
assoc > C:\lists.txt
assoc | find “.doc” > C:\listsdoc.txt

Output
.doc=Word.Document.8
.dochtml=wordhtmlfile
.docm=Word.DocumentMacroEnabled.12
.docmhtml=wordmhtmlfile
.docx=Word.Document.12
.docxml=wordxmlfile
3 CD

This batch command helps in making changes to a


different directory, or displays the current directory.

Syntax
cd
4 CLS
54

Batch scripting tutorial


This batch command clears the screen.

Example
@echo off
Cls
5 COPY

This batch command is used for copying files from one


location to the other.

Example
The following example shows the different variants of
the copy command.
@echo off
cd
Rem Copies lists.txt to the present working directory.
If there is no destination identified , it defaults to the
present working directory.
copy c:\lists.txt
Rem The file lists.txt will be copied from C:\ to C:\tp
location
copy C:\lists.txt c:\tp
Rem Quotation marks are required if the file name
contains spaces
copy “C:\My File.txt”
Rem Copies all the files in F drive which have the txt file
extension to the
current working directory copy
F:\*.txt
Rem Copies all files from dirA to dirB. Note that
directories nested in dirA will not be copied
copy C:\dirA dirB
6 DEL

This batch command deletes files and not directories.

Example
The following example shows the different variants of
55

Batch scripting tutorial


the del command.
@echo off
Rem Deletes the file lists.txt in C:\
del C:\lists.txt
Rem Deletes all files recursively in all nested directories
del /s *.txt
Rem Deletes all files recursively in all nested directories ,
but asks for the
confirmation from the user first
Del /p /s *.txt
7 DIR

This batch command lists the contents of a directory.

Example
@echo off
Rem All the directory listings from C:\ will be routed to
the file lists.txt
dir C:\>C:\lists.txt
Rem Lists all directories and subdirectories recursively
dir /s
Rem Lists the contents of the directory and all
subdirectories recursively, one
file per line, displaying complete path for each listed file
or directory.
dir /s /b
Rem Lists all files with .txt extension.
dir *.txt
Rem Includes hidden files and system files in the listing.
dir /a
Rem Lists hidden files only.
dir /ah
8 DATE

This batch command help to find the system date.

Example
@echo off
echo %DATE%
56

Batch scripting tutorial


Output
The current date will be displayed in the command
prompt. For example,
Mon 12/28/2021
9 ECHO

This batch command displays messages, or turns


command echoing on or off.

Example
Rem Turns the echo on so that each command will be
shown as executed
echo on
echo "Hello World"

Rem Turns the echo off so that each command will not
be shown when executed
@echo off
echo "Hello World"

Rem Displays the contents of the PATH variable


echo %PATH%
10 EXIT

This batch command exits the DOS console.

Example
@echo off
echo "Hello World"
exit
11 MD

This batch command creates a new directory in the


current location.

Syntax
md [new directory name]
12 MOVE
57

Batch scripting tutorial


This batch command moves files or directories between
directories.

Syntax
move [source] [destination]
The files will be copied from source to destination
location.

Example
The following example shows the different variants of
the move command.
@echo off
Rem Moves the file list.txt to the directory c:\tp
move C:\lists.txt c:\tp
Rem Renames directory Dir1 to Dir2, assuming Dir1 is a
directory and Dir2 does not exist.
move Dir1 Dir2
Rem Moves the file lists.txt to the current directory.
move C:\lists.txt
13 PATH

This batch command displays or sets the path variable.

Example
@echo off
Echo %PATH%
14 PAUSE

This batch command prompts the user and waits for a


line of input to be entered.

Syntax
Pause
15 PROMPT

This batch command can be used to change or reset the


cmd.exe prompt.

Example
58

Batch scripting tutorial


@echo off
prompt myprompt$G
16 RD

This batch command removes directories, but the


directories need to be empty before they can be
removed.

Example
The following example shows the different variants of
the rd command.
@echo off
Rem removes the directory called newdir
rd C:\newdir

Rem removes 2 directories


rd Dir1 Dir2

Rem Removes directory with spaces


rd "Application A"

Rem Removes the directory Dir1 including all the files


and subdirectories in it rd /s Dir1
Rem Removes the directory Dir1 including all the files
and subdirectories in it but
asks for a user confirmation first.
rd /q /s Dir1
17 REN

Renames files and directories

Example
@echo off
ren C:\lists.txt C:\newlists.txt
18 REM

This batch command is used for remarks in batch files,


preventing the content of the remark from being
executed.
59

Batch scripting tutorial


Example
@echo off
REM This is a batch file

Output
None
19 START

This batch command starts a program in new window,


or opens a document.

Syntax
START “programname”
Example
@echo off
start notepad.exe

Output
When the batch file is executed, a new notepad
windows will start.

20 TIME

This batch command sets or displays the time.

Example
@echo off
echo %TIME%

Output
The current system time will be displayed. For example,
22:06:52.87
21 TYPE

This batch command prints the content of a file or files


to the output.
60

Batch scripting tutorial


Syntax
TYPE [filename]
Where filename is the file whose contents need to be displayed.

Example
@echo off
TYPE C:\tp\lists.txt

22 VOL

This batch command displays the volume labels.


Example
@echo off
VOL

Output
The output will display the current volume label. For example,
Volume in drive C is Windows8_OS
Volume Serial Number is E41C-6F43
23 ATTRIB

Displays or sets the attributes of the files in the curret


directory

Syntax
attrib
24 CHKDSK

This batch command checks the disk for any problems.

Example
@echo off
chkdsk

25 CHOICE

This batch command provides a list of options to the


user.

Example
@echo off
61

Batch scripting tutorial


echo "What is the file size you what"
echo "A:10MB"
echo "B:20MB"
echo "C:30MB"
choice /c ABC /m "What is your option A , B or C"

Output
The above program produces the following output.
"What is the file size you what"
"A:10MB"
"B:20MB"
"C:30MB"
What is your option A , B or C [A,B,C]?
26 CMD

This batch command invokes another instance of


command prompt.

Example
@echo off
cmd

27 COMP

This batch command compares 2 files based on the file


size.

Example
@echo off

COMP C:\tp\lists.txt C:\tp\listsA.txt

28 CONVERT

This batch command converts a volume from FAT16 or


FAT32 file system to NTFS file system.

Syntax
CONVERT [drive]

Example
@echo off
CONVERT C:\

29 DRIVERQUERY
62

Batch scripting tutorial


This batch command shows all installed device drivers
and their properties.

Example
@echo off
driverquery

Output
The above command will display the information of all the device
drivers installed on the current system. Following is an example
of a subset of the information displayed.
WacomPen Wacom Serial Pen HID D Kernel 8/22/2013 4:39:15
AM
Wanarp Remote Access IP ARP D Kernel 8/22/2013 4:35:45
AM
Wanarpv6 Remote Access IPv6 ARP Kernel 8/22/2013 4:35:45
AM
Wdf01000 Kernel Mode Driver Fra Kernel 8/22/2013 4:38:56
AM
WFPLWFS Microsoft Windows Filt Kernel 11/9/2014 6:57:28
PM
WIMMount File System 8/22/2013 4:39:34 AM
WinMad WinMad Service Kernel 5/9/2013 9:14:27 AM
WinNat Windows NAT Driver Kernel 1/22/2014 1:10:49 AM
WinUsb Driver Kernel 8/22/2013 4:37:55 AM
WinVerbs Service Kernel 5/9/2013 9:14:30 AM
WmiAcpi Microsoft Windows Mana Kernel 8/22/2013 4:40:04
AM
WpdUpFltr WPD Upper Class Filter Kernel 8/22/2013 4:38:45
AM
ws2ifsl Windows Socket 2.0 Non Kernel 8/22/2013 4:40:03
AM
wtlmdrv Microsoft iSCSI Target Kernel 8/22/2013 4:39:19 AM
WudfPf User Mode Driver Frame Kernel 8/22/2013 4:37:21
AM
WUDFWpdFs WUDFWpdFs Kernel 8/22/2013 4:36:50
AM
WUDFWpdMtp WUDFWpdMtp Kernel 8/22/2013 4:36:5
30 EXPAND

This batch command extracts files from


compressed .cab cabinet files.

Example
63

Batch scripting tutorial


@echo off
EXPAND excel.cab

31 FIND

This batch command searches for a string in files or


input, outputting matching lines.

Example
@echo off
FIND "Application" C:\tp\lists.txt

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.

Syntax
format [drive]
Where drive is the drive which needs to be formatted.

Example
@echo off
format D:\

33 HELP

This batch command shows the list of Windows-supplied


commands.

Example
@echo off
help

Output
The above command will display a list of all commands and their
description. Following is an example of a subset of the output.
SCHTASKS Schedules commands and programs to run on a
computer.
SHIFT Shifts the position of replaceable parameters in batch files.
SHUTDOWN Allows proper local or remote shutdown of machine.
SORT Sorts input.
START Starts a separate window to run a specified program or
command.
64

Batch scripting tutorial


SUBST Associates a path with a drive letter.
SYSTEMINFO Displays machine specific properties and configuration.
TASKLIST Displays all currently running tasks including services.
TASKKILL Kill or stop a running process or application.
TIME Displays or sets the system time.
TITLE Sets the window title for a CMD.EXE session.
TREE Graphically displays the directory structure of a drive or
path.
TYPE Displays the contents of a text file.
VER Displays the Windows version.
VERIFY Tells Windows whether to verify that your files are written
correctly to a disk.
VOL Displays a disk volume label and serial number.
XCOPY Copies files and directory trees.
WMIC Displays WMI information inside interactive command
shell.

For more information on tools see the command-line reference in the


online help.
34 IPCONFIG

This batch command displays Windows IP Configuration.


Shows configuration by connection and the name of that
connection.

Example
@echo off
ipconfig

Output
The above command will display the Windows IP configuration on
the current machine. Following is an example of the output.
Windows IP Configuration

Wireless LAN adapter Local Area Connection* 11:


Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :

Ethernet adapter Ethernet:


Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :

Wireless LAN adapter Wi-Fi:


Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :

Tunnel adapter Teredo Tunneling Pseudo-Interface:


Media State . . . . . . . . . . . : Media disconnected
65

Batch scripting tutorial


Connection-specific DNS Suffix . :
35 LABEL

This batch command adds, sets or removes a disk label.

Example
@echo off
label
36 MORE

This batch command displays the contents of a file or


files, one screen at a time.

Example
@echo off
More C:\tp\lists.txt
Directory of C:\Program Files

Output
The above command will display the contents of the file lists.txt
one screen at a time. Following is an example of an output. Note
the -- More (12%) – at the end of the screen. In order to proceed
and display the remaining contents of the file, you need to enter
a key.
12/22/2015 02:31 AM <DIR> .
12/22/2015 02:31 AM <DIR> ..
12/15/2015 11:14 PM <DIR> Application Verifier
12/18/2015 05:06 PM <DIR> Bonjour
12/26/2015 08:01 PM <DIR> CCleaner
12/18/2015 05:05 PM <DIR> Common Files
12/17/2015 11:04 AM <DIR> Git
12/15/2015 11:09 PM <DIR> IIS
12/15/2015 11:10 PM <DIR> IIS Express
12/15/2015 10:16 PM <DIR> Intel
03/18/2014 02:24 AM <DIR> Internet Explorer
12/18/2015 05:06 PM <DIR> iPod
12/18/2015 05:06 PM <DIR> iTunes
12/15/2015 11:16 PM <DIR> Microsoft Identity Extensions
12/15/2015 11:46 PM <DIR> Microsoft Office
12/22/2015 02:31 AM <DIR> Microsoft Silverlight
12/15/2015 11:15 PM <DIR> Microsoft SQL Server
12/15/2015 11:15 PM <DIR> Microsoft SQL Server Compact
Edition
12/15/2015 10:59 PM <DIR> Microsoft Visual Studio 12.0
-- More (12%) --
37 NET
66

Batch scripting tutorial


Provides various network services, depending on the
command used.

Syntax
NET [variant]
Where its variants can be one of the following −

 net accounts
 net computer
 net config
 net continue
 net file
 net group
 net help
 net helpmsg
 net localgroup
 net name
 net pause
 net print
 net send
 net session
 net share
 net start
 net statistics
 net stop
 net time
 net use
 net user
 net view

Example
@echo off
Net user

Output
The above command will display the current accounts defined on
the system. Following is an example of an output.
User accounts for \\WIN-50GP30FGO75

-------------------------------------------------------------------------------
Administrator atlbitbucket Guest
67

Batch scripting tutorial


The command completed successfully.
38 PING

This batch command sends ICMP/IP "echo" packets over


the network to the designated address.

Syntax
PING [address]
Where address is the IP address or hostname of the destination
system.

Example
@echo off
Ping 127.0.0.1

Output
The above command will send ICMP/IP "echo" packets to the
destination address 192.168.0.1. Following is an example of the
output.
Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes = 32 time<1ms TTL = 128
Reply from 127.0.0.1: bytes = 32 time<1ms TTL = 128
Reply from 127.0.0.1: bytes = 32 time<1ms TTL = 128
Reply from 127.0.0.1: bytes = 32 time<1ms TTL = 128

Ping statistics for 127.0.0.1:


Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
39 SHUTDOWN

This batch command shuts down a computer, or logs off


the current user.

Example
@echo off
shutdown

Output
If the user executing the batch files has the relevant rights, the
computer will be shutdown.

40 SORT
68

Batch scripting tutorial


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.

Syntax
Sort [filename]
Where filename is the file whose contents need to be sorted.

Example
@echo off
Sort C:\tp\lists.txt

41 SUBST

This batch command assigns a drive letter to a local


folder, displays current assignments, or removes an
assignment.

Syntax
Subst [driveletter]

Example
@echo off
Subst p:

42 SYSTEMINFO

This batch command shows configuration of a computer


and its operating system.

Example
@echo off
systeminfo

Output
The above command will show the system information on the
current system. Following is a subset of the output.
Host Name: WIN-50GP30FGO75
OS Name: Microsoft Windows Server 2012 R2 Standard
OS Version: 6.3.9600 N/A Build 9600
OS Manufacturer: Microsoft Corporation
OS Configuration: Standalone Server
OS Build Type: Multiprocessor Free
Registered Owner: Windows User
Registered Organization:
69

Batch scripting tutorial


Product ID: 00252-70000-00000-AA535
Original Install Date: 12/13/2015, 12:10:16 AM
System Boot Time: 12/28/2015, 4:43:04 PM
System Manufacturer: LENOVO
System Model: 20287
System Type: x64-based PC
43 TASKKILL

This batch command ends one or more tasks.

Syntax
Taskkill /im [taskname]

Example
@echo off

Taskkill /im mspaint.exe

44 TASKLIST

This batch command lists tasks, including task name


and process id (PID).

Example
@echo off
Tasklist

45 XCOPY

This batch command copies files and directories in a


more advanced way.

Syntax
Xcopy [source][destination]

Example
Xcopy c:\lists.txt c:\tp\

46 TREE

This batch command displays a tree of all subdirectories


of the current directory to any level of recursion or
depth.

Example
70

Batch scripting tutorial


@echo off
tree

Output
The above command will display the tree structure of the current
directory. Following is an example of the output.
Folder PATH listing for volume Windows8_OS
Volume serial number is E41C-6F43
C:.
├───newdir
├───newdir1
└───newdir2
47 FC

This batch command lists the actual differences


between two files.

Syntax
Fc [fileA] [fileB]
Where fileA and fileB are 2 files that need to be compared.

Example
@echo off
FC lists.txt listsA.txt

48 DISKPART

This batch command shows and configures the


properties of disk partitions.

Example
@echo off
diskpart

Output
The above command shows the properties of disk partitions.
Following is an example of the output.
Microsoft DiskPart version 6.3.9600

Copyright (C) 1999-2013 Microsoft Corporation.


On computer: WIN-50GP30FGO75
49 TITLE
71

Batch scripting tutorial


This batch command sets the title displayed in the
console window.

Example
@echo off
Title “New Windows Title”

50 SET

Displays the list of environment variables on the current


system.

Example
@echo off
set

You might also like