Batch Script Book PDF
Batch Script Book PDF
Batch Script Book PDF
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 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
Typically, to create a batch file, notepad is used. This is the simplest tool for creation of
batch files. Next is the execution environment for the batch scripts. On Windows systems,
this is done via the command prompt or cmd.exe. All batch files are run in this environment.
Method 2 − Via the run command – The following snapshot shows to find the command
prompt(cmd.exe) on Windows server 2012.
Once the cmd.exe is launched, you will be presented with the following screen. This will be
your environment for executing your batch scripts.
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.
In this chapter, we will look at some of the frequently used batch commands.
VER
1 This batch command shows the version of MS-DOS you are using.
ASSOC
2 This is a batch command that associates an extension with a file type (FTYPE),
displays existing associations, or deletes an association.
CD
3 This batch command helps in making changes to a different directory, or displays
the current directory.
CLS
4 This batch command clears the screen.
COPY
5 This batch command is used for copying files from one location to the other.
DEL
6 This batch command deletes files and not directories.
DIR
7 This batch command lists the contents of a directory.
DATE
8 This batch command help to find the system date.
ECHO
9 This batch command displays messages, or turns command echoing on or off.
EXIT
10 This batch command exits the DOS console.
MD
11 This batch command creates a new directory in the current location.
MOVE
12 This batch command moves files or directories between directories.
PATH
13 This batch command displays or sets the path variable.
PAUSE
14 This batch command prompts the user and waits for a line of input to be entered.
PROMPT
15 This batch command can be used to change or reset the cmd.exe prompt.
RD
16 This batch command removes directories, but the directories need to be empty
before they can be removed.
REN
17 Renames files and directories
REM
18 This batch command is used for remarks in batch files, preventing the content of
the remark from being executed.
START
19 This batch command starts a program in new window, or opens a document.
TIME
20 This batch command sets or displays the time.
TYPE
21 This batch command prints the content of a file or files to the output.
VOL
22 This batch command displays the volume labels.
ATTRIB
23 Displays or sets the attributes of the files in the curret directory
CHKDSK
24 This batch command checks the disk for any problems.
CHOICE
25 This batch command provides a list of options to the user.
CMD
26 This batch command invokes another instance of command prompt.
COMP
27 This batch command compares 2 files based on the file size.
CONVERT
28 This batch command converts a volume from FAT16 or FAT32 file system to NTFS
file system.
DRIVERQUERY
29 This batch command shows all installed device drivers and their properties.
EXPAND
30 This batch command extracts files from compressed .cab cabinet files.
FIND
31 This batch command searches for a string in files or input, outputting matching
lines.
FORMAT
32 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.
HELP
33 This batch command shows the list of Windows-supplied commands.
IPCONFIG
LABEL
35 This batch command adds, sets or removes a disk label.
MORE
36 This batch command displays the contents of a file or files, one screen at a time.
NET
37 Provides various network services, depending on the command used.
PING
38 This batch command sends ICMP/IP "echo" packets over the network to the
designated address.
SHUTDOWN
39 This batch command shuts down a computer, or logs off the current user.
SORT
40 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.
SUBST
41 This batch command assigns a drive letter to a local folder, displays current
assignments, or removes an assignment.
Advertisements
This batch command shows the version of MS-DOS you are using.
ver
@echo off
ver
The output of the above command is as follows. The version number will depend upon the
operating system you are working on.
This is a batch command that associates an extension with a file type (FTYPE), displays
existing associations, or deletes an association.
@echo off
assoc > C:\lists.txt
assoc | find “.doc” > C:\listsdoc.txt
The list of file associations will be routed to the file lists.txt. The following output shows
what is there in the listsdoc.txt file after the above batch file is run.
.doc=Word.Document.8
.dochtml=wordhtmlfile
.docm=Word.DocumentMacroEnabled.12
.docmhtml=wordmhtmlfile
.docx=Word.Document.12
.docxml=wordxmlfile
Advertisements
This batch command helps in making changes to a different directory, or displays the
current directory.
cd
The following example shows how the cd command can be used in a variety of ways.
@echo off
Rem The cd without any parameters is used to display the current working directory
cd
Rem Changing the path to Program Files
cd\Program Files
cd
Rem Changing the path to Program Files
cd %USERPROFILE%
cd
Rem Changing to the parent directory
cd..
cd
Rem Changing to the parent directory two levels up
cd..\..
cd
The above command will display the following output after changing to the various folder
locations.
C:\Users\Administrator
C:\Program Files
C:\Users\Administrator
C:\Users
C:\
Advertisements
cls
@echo off
Cls
This batch command is used for copying files from one location to the other.
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
All actions are performed as per the remarks in the batch file.
Advertisements
del [filename]
The following example shows the different variants of 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
All actions are performed as per the remarks in the batch file.
Advertisements
dir
The following example shows the different variants of the dir command.
@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
All actions are performed as per the remarks in the batch file.
Advertisements
DATE
@echo off
echo %DATE%
The current date will be displayed in the command prompt. For example,
Mon 12/28/2015
Advertisements
ECHO “string”
The following example shows the different variants of the dir command.
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"
C:\>Rem Turns the echo on so that each command will be shown as executed
C:\>echo on
C:\>Rem Turns the echo off so that each command will not be shown when executed
"Hello World"
Advertisements
Exit
@echo off
echo "Hello World"
exit
The batch file will terminate and the command prompt window will close.
Advertisements
@echo off
md newdir
cd newdir
cd Rem “Goes back to the parent directory and create 2 directories”
cd..
md newdir1 newdir1
cd newdir1
cd
cd..
cd newdir2
cd
C:\newdir
C:\newdir1
C:\newdir2
Advertisements
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
All actions are performed as per the remarks in the batch file.
Advertisements
PATH
@echo off
Echo %PATH%
The value of the path variable will be displayed in the command prompt.
Advertisements
This batch command prompts the user and waits for a line of input to be entered.
Pause
@echo off
pause
The command prompt will show the message “Press any key to continue….” to the user and
wait for the user’s input.
Advertisements
This batch command can be used to change or reset the cmd.exe prompt.
PROMPT [newpromptname]
@echo off
prompt myprompt$G
The $G is the greater than sign which is added at the end of the prompt.
This batch command removes directories, but the directories need to be empty before they
can be removed.
rd [directoryname]
@echo off
Rem removes the directory called newdir
rd C:\newdir
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
All actions are performed as per the remarks in the batch file.
Advertisements
Renames the file name from the old file/dir name to the new one.
@echo off
ren C:\lists.txt C:\newlists.txt
This batch command is used for remarks in batch files, preventing the content of the remark
from being executed.
@echo off
REM This is a batch file
None
Advertisements
START “programname”
@echo off
start notepad.exe
When the batch file is executed, a new notepad windows will start.
Advertisements
TIME
@echo off
echo %TIME%
22:06:52.87
Advertisements
This batch command prints the content of a file or files to the output.
TYPE [filename]
@echo off
TYPE C:\tp\lists.txt
The contents of the file lists.txt will be displayed to the command prompt.
Advertisements
VOL
@echo off
VOL
The output will display the current volume label. For example,
attrib
The following example shows the different variants of the attrib command.
@echo off
Rem Displays the attribites of the file in the current directory
Attrib
For example,
A C:\tp\assoclst.txt
A C:\tp\List.cmd
A C:\tp\lists.txt
A C:\tp\listsA.txt
A C:\tp\lists.txt
A R C:\tp\lists.txt
R C:\tp\lists.txt
Advertisements
chkdsk
@echo off
chkdsk
The above command starts checking the current disk for any errors.
Advertisements
Where Options is the list of options to provide to the user and Message is the string
message which needs to be displayed.
@echo off
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"
cmd
@echo off
cmd
Wherein sourceA and sourceB are the files which need to be compared.
@echo off
COMP C:\tp\lists.txt C:\tp\listsA.txt
The above command will compare the files lists.txt and listsA.txt and find out if the two file
sizes are different.
Advertisements
This batch command converts a volume from FAT16 or FAT32 file system to NTFS file
system.
CONVERT [drive]
@echo off
CONVERT C:\
This batch command shows all installed device drivers and their properties.
driverquery
@echo off
driverquery
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.
This batch command extracts files from compressed .cab cabinet files.
EXPAND [cabinetfilename]
@echo off
EXPAND excel.cab
The above command will extract the contents of the file excel.cab in the current location.
Advertisements
This batch command searches for a string in files or input, outputting matching lines.
Where text is the string which needs to be searched for and destination is the source in
which the search needs to take place.
@echo off
FIND "Application" C:\tp\lists.txt
If the word “Application” resides in the file lists.txt, the line containing the string will be
displayed in the command prompt.
Advertisements
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.
format [drive]
@echo off
format D:\
help
@echo off
help
The above command will display a list of all commands and their description. Following is an
example of a subset of the output.
ipconfig
@echo off
ipconfig
The above command will display the Windows IP configuration on the current machine.
Following is an example of the output.
Windows IP Configuration
Label
@echo off
label
The above command will prompt the user to enter a new label for the current drive.
Advertisements
This batch command displays the contents of a file or files, one screen at a time.
More [filename]
Where filename is the file whose contents need to be listed one screen at a time.
@echo off
More C:\tp\lists.txt
Directory of C:\Program Files
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.
NET [variant]
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
@echo off
Net user
The above command will display the current accounts defined on the system. Following is an
example of an output.
-------------------------------------------------------------------------------
Administrator atlbitbucket Guest
The command completed successfully.
Advertisements
This batch command sends ICMP/IP "echo" packets over the network to the designated
address.
PING [address]
@echo off
Ping 127.0.0.1
The above command will send ICMP/IP "echo" packets to the destination address
192.168.0.1. Following is an example of the output.
This batch command shuts down a computer, or logs off the current user.
shutdown
@echo off
shutdown
If the user executing the batch files has the relevant rights, the computer will be shutdown.
Advertisements
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.
Sort [filename]
@echo off
Sort C:\tp\lists.txt
Advertisements
This batch command assigns a drive letter to a local folder, displays current assignments, or
removes an assignment.
Subst [driveletter]
@echo off
Subst p:
This batch command shows configuration of a computer and its operating system.
systeminfo
@echo off
systeminfo
The above command will show the system information on the current system. Following is a
subset of the output.
@echo off
Taskkill /im mspaint.exe
The above command will send a termination message to any open programs of MS Paint.
Advertisements
This batch command lists tasks, including task name and process id (PID).
Tasklist
@echo off
Tasklist
The above command will list all the tasks on the current system.
Advertisements
This batch command copies files and directories in a more advanced way.
Xcopy [source][destination]
The above command will copy the file lists.txt to the tp folder.
Advertisements
This batch command displays a tree of all subdirectories of the current directory to any level
of recursion or depth.
Tree
@echo off
tree
The above command will display the tree structure of the current directory. Following is an
example of the output.
This batch command lists the actual differences between two files.
Fc [fileA] [fileB]
@echo off
FC lists.txt listsA.txt
The above command will display the differences in the contents of the files (lists.txt and
listsA.txt ) if any.
Advertisements
This batch command shows and configures the properties of disk partitions.
Diskpart
@echo off
diskpart
The above command shows the properties of disk partitions. Following is an example of the
output.
This batch command sets the title displayed in the console window.
TITLE [Tilename]
Where tilename is the new name to be given to the title of the command prompt window.
@echo off
Title “New Windows Title”
The above command will change the title of the window to “New Windows Title”.
Advertisements
Set
@echo off
set
The above command displays the list of environment variables on the current system.
After your batch file is created, the next step is to save your batch file. Batch files have the
extension of either .bat or .cmd. Some general rules to keep in mind when naming batch
files −
Try to avoid spaces when naming batch files, it sometime creates issues when they
are called from other scripts.
Don’t name them after common batch files which are available in the system such
as ping.cmd.
The above screenshot shows how to save the batch file. When saving your batch file a few
points to keep in mind.
Remember to put the .bat or .cmd at the end of the file name.
Step 3 − Right-click the file and choose the “Edit” option from the context menu.
The file will open in Notepad for further editing.
Normally, the first line in a batch file often consists of the following 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.
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.
Let’s construct our simple first batch script program. Open notepad and enter the following
lines of code. Save the file as “List.cmd”.
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.
There are two types of variables in batch files. One is for parameters which can be passed
when the batch file is called and the other is done via the set command.
Batch scripts support the concept of command line arguments wherein arguments can be
passed to the batch file when invoked. The arguments can be called from the batch files
through the variables %1, %2, %3, and so on.
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
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.
The other way in which variables can be initialized is via the ‘set’ command. Following is the
syntax of the set command.
set /A variable-name=value
where,
The following example shows a simple way the set command can be used.
@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.
Hello World
In batch script, it is also possible to define a variable to hold a numeric value. This can be
done by using the /A switch.
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.
@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
In any programming language, there is an option to mark variables as having some sort of
scope, i.e. the section of code on which they can be accessed. Normally, variable having a
global scope can be accessed anywhere from a program whereas local scoped variables
have a defined boundary in which they can be accessed.
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.
@echo off
set globalvar = 5
SETLOCAL
set var = 13145
set /A var = %var% + 5
echo %var%
echo %globalvar%
ENDLOCAL
The ‘globalvar’ is defined with a global scope and is available throughout the entire
script.
You will notice that the command echo %var% will not yield anything because after the
ENDLOCAL statement, the ‘var’ variable will no longer exist.
If you have variables that would be used across batch files, then it is always preferable to
use environment variables. Once the environment variable is defined, it can be accessed via
the % sign. The following example shows how to see the JAVA_HOME defined on a system.
The JAVA_HOME variable is a key component that is normally used by a wide variety of
applications.
@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
It’s always a good practice to add comments or documentation for the scripts which are
created. This is required for maintenance of the scripts to understand what the script
actually does.
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.
ECHO OFF
IF NOT "%OS%"=="Windows_NT" GOTO Syntax
ECHO.%* | FIND "?" >NUL
IF NOT ERRORLEVEL 1 GOTO Syntax
IF NOT [%2]==[] GOTO Syntax
SETLOCAL
SET WSS=
IF NOT [%1]==[] FOR /F "tokens = 1 delims = \ " %%A IN ('ECHO.%~1') DO SET WSS = %%A
FOR /F "tokens = 1 delims = \ " %%a IN ('NET VIEW ^| FIND /I "\\%WSS%"') DO FOR /F
"tokens = 1 delims = " %%A IN ('NBTSTAT -a %%a ^| FIND /I /V "%%a" ^| FIND "<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
There are two ways to create comments in Batch Script; one is via the Rem command. Any
text which follows the Rem statement will be treated as comments and will not be executed.
Following is the general syntax of this statement.
Rem Remarks
The following example shows a simple way the Rem command can be used.
@echo off
Rem This program just displays Hello World
set message=Hello World
echo %message%
The above command produces the following output. You will notice that the line with the
Rem statement will not be executed.
Hello World
The other way to create comments in Batch Script is via the :: command. Any text which
follows the :: statement will be treated as comments and will not be executed. Following is
the general syntax of this statement.
:: Remarks
The following example shows a simple way the Rem command can be used.
@echo off
:: This program just displays Hello World
set message = Hello World
echo %message%
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
:: Keep variable local
SETLOCAL
:: Initialize variable
SET WSS=
:: Parse command line parameter
IF NOT [%1]==[] FOR /F "tokens = 1 delims = \ " %%A IN ('ECHO.%~1') DO SET WSS = %%A
:: Use NET VIEW and NBTSTAT to find computers and logged on users
FOR /F "tokens = 1 delims = \ " %%a IN ('NET VIEW ^| FIND /I "\\%WSS%"') DO FOR /F
"tokens = 1 delims = " %%A IN ('NBTSTAT -a %%a ^| FIND /I /V "%%a" ^| FIND
"<03>"') DO ECHO.%%a %%A
:: Done
ENDLOCAL
GOTO:EOF
:Syntax
ECHO Display logged on users and their workstations.
ECHO Usage: ACTUSR [ filter ]
IF "%OS%"=="Windows_NT" ECHO Where: filter is the first part of the
computer name^(s^) to be displayed
You can now see that the code has become more understandable to users who have not
developed the code and hence is more maintainable.
Create String
1 A string can be created in DOS in the following way.
Empty String
2 Empty String
String Interpolation
3 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.
String Concatenation
You can use the set operator to concatenate two strings or a string and a
4 character, or two characters. Following is a simple example which shows how to
use string concatenation.
String length
In DOS scripting, there is no length function defined for finding the length of a
5 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.
toInt
A variable which has been set as string using the set variable can be converted to
6 an integer using the /A switch which is using the set variable. The following
example shows how this can be accomplished.
Align Right
7 This used to align text to the right, which is normally used to improve readability
of number columns.
Left String
8 This is used to extract characters from the beginning of a string.
Mid String
9 This is used to extract a substring via the position of the characters in the string.
Remove
10 The string substitution feature can also be used to remove a substring from
another string.
Replace a String
13 To replace a substring with another string use the string substitution feature.
Advertisements
@echo off
:: This program just displays Hello World
set message = Hello World
echo %message%
Hello World
Advertisements
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.
@echo off
SET a=
SET b = Hello
if [%a%]==[] echo "String A is empty"
if [%b%]==[] echo "String B is empty "
String A is empty
Advertisements
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.
@echo off
SET a = Hello
SET b = World
SET /A d = 50
SET c=%a% and %b% %d%
echo %c%
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.
@echo off
SET a = Hello
SET b = World
SET c=%a% and %b%
echo %c%
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.
@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.
11
Advertisements
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.
@echo off
set var = 13145
set /A var=%var% + 5
echo %var%
13150
Apart from this, strings have the following implementations which are available. Batch
scripts have the following commands which are used to carry out string manipulation in
strings.
%variable:~num_chars_to_skip%
%variable:~num_chars_to_skip,num_chars_to_keep%
%variable:~num_chars_to_skip, -num_chars_to_keep%
%variable:~-num_chars_to_skip,num_chars_to_keep%
%variable:~-num_chars_to_skip,-num_chars_to_keep%
Let us discuss the possible string operations that can be performed by using the above
commands.
Advertisements
This used to align text to the right, which is normally used to improve readability of number
columns.
@echo off
set x = 1000
set y = 1
set y = %y%
echo %x%
set y = %y:~-4%
echo %y%
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.
The above command produces the following output. The key thing to note is that the value
of 2 is aligned to match the units columns when displaying numbers.
1000
1
Advertisements
@echo off
set str = Helloworld
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.
Helloworld
Hello
Advertisements
This is used to extract a substring via the position of the characters in the string.
@echo off
set str = Helloworld
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.
Helloworld
world
Advertisements
The string substitution feature can also be used to remove a substring from another string.
@echo off
set str = Batch scripts is easy. It is really easy.
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.
This is used to remove the first and the last character of a string
@echo off
set str = Batch scripts is easy. It is really easy
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.
@echo off
set str = This string has a lot of spaces
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.
To replace a substring with another string use the string substitution feature.
@echo off
set str = This message needs changed.
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%
@echo off
set str = This message needs changed.
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.
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]%
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.
@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
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.
Comments
variables
Arrays
Decision making
Time and date
Operators
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%
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.
@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.
Name = Joe
Advertisements
The first decision-making statement is the ‘if’ statement. The general form of this statement
in Batch Script is as follows −
if(condition) do_something
The general working of this statement is that first a condition is evaluated in the ‘if’
statement. If the condition is true, it then executes the statements. The following diagram
shows the flow of the if statement.
One of the common uses for the ‘if’ statement in Batch Script is for checking variables which
are set in Batch Script itself. The evaluation of the ‘if’ statement can be done for both
strings and numbers.
The following example shows how the ‘if’ statement can be used for numbers.
Example
@echo off
SET /A a = 5
SET /A b = 10
SET /A c = %a% + %b%
if %c%==15 echo "The value of variable c is 15"
if %c%==10 echo "The value of variable c is 10"
The first ‘if’ statement checks if the value of the variable c is 15. If so, then it echo’s
a string to the command prompt.
Since the condition in the statement - if %c% == 10 echo "The value of variable c is
10 evaluates to false, the echo part of the statement will not be executed.
Output
15
The following example shows how the ‘if’ statement can be used for strings.
Example
@echo off
SET str1 = String1
SET str2 = String2
if %str1%==String1 echo "The value of variable String1"
if %str2%==String3 echo "The value of variable c is String3"
The first ‘if’ statement checks if the value of the variable str1 contains the string
“String1”. If so, then it echo’s a string to the command prompt.
Since the condition of the second ‘if’ statement evaluates to false, the echo part of
the statement will not be executed.
Output
Note − One key thing to note is that the evaluation in the ‘if’ statement is "case-sensitive”.
The same program as above is modified a little as shown in the following example. In the
first statement, we have changed the comparison criteria. Because of the different casing,
the output of the following program would yield nothing.
@echo off
SET str1 = String1
SET str2 = String2
if %str1%==StrinG1 echo "The value of variable String1"
if %str2%==String3 echo "The value of variable c is String3"
Another common use of the ‘if’ statement is used to check for the values of the command
line arguments which are passed to the batch files. The following example shows how the ‘if’
statement can be used to check for the values of the command line arguments.
Example
@echo off
echo %1
echo %2
echo %3
if %1%==1 echo "The value is 1"
if %2%==2 echo "The value is 2"
if %3%==3 echo "The value is 3"
The above program assumes that 3 command line arguments will be passed when
the batch script is executed.
A comparison is done for each command line argument against a value. If the
criteria passes then a string is sent as the output.
Output
If the above code is saved in a file called test.bat and the program is executed as
test.bat 1 2 3
1
2
3
"The value is 1"
"The value is 2"
"The value is 3"
Advertisements
The next decision making statement is the If/else statement. Following is the general form
of this statement.
The general working of this statement is that first a condition is evaluated in the ‘if’
statement. If the condition is true, it then executes the statements thereafter and stops
before the else condition and exits out of the loop. If the condition is false, it then executes
the statements in the else statement block and then exits the loop. The following diagram
shows the flow of the ‘if’ statement.
Just like the ‘if’ statement in Batch Script, the if-else can also be used for checking variables
which are set in Batch Script itself. The evaluation of the ‘if’ statement can be done for both
strings and numbers.
The following example shows how the ‘if’ statement can be used for numbers.
Example
@echo off
SET /A a = 5
SET /A b = 10
SET /A c = %a% + %b%
if %c%==15 (echo "The value of variable c is 15") else (echo "Unknown value")
if %c%==10 (echo "The value of variable c is 10") else (echo "Unknown value")
Each ‘if else’ code is placed in the brackets (). If the brackets are not placed to
separate the code for the ‘if and else’ code, then the statements would not be valid
proper if else statements.
In the first ‘if else’ statement, the if condition would evaluate to true.
In the second ‘if else’ statement, the else condition will be executed since the
criteria would be evaluated to false.
Output
The same example can be repeated for strings. The following example shows how the ‘if
else’ statement can be used to strings.
Example
@echo off
SET str1 = String1
SET str2 = String2
if %str1%==String1 (echo "The value of variable String1") else (echo "Unknown value")
if %str2%==String3 (echo "The value of variable c is String3") else (echo "Unknown value")
The first ‘if’ statement checks if the value of the variable str1 contains the string
“String1”. If so, then it echo’s a string to the command prompt.
Since the condition of the second ‘if’ statement evaluates to false, the echo part of
the statement will not be executed.
Output
The ‘if else’ statement can also be used for checking of command line arguments. The
following example show how the ‘if’ statement can be used to check for the values of the
command line arguments.
Example
@echo off
echo %1
echo %2
echo %3
if %1%==1 (echo "The value is 1") else (echo "Unknown value")
if %2%==2 (echo "The value is 2") else (echo "Unknown value")
if %3%==3 (echo "The value is 3") else (echo "Unknown value")
Output
If the above code is saved in a file called test.bat and the program is executed as
test.bat 1 2 4
1
2
4
"The value is 1"
"The value is 2"
"Unknown value"
A special case for the ‘if’ statement is the "if defined", which is used to test for the existence
of a variable. Following is the general syntax of the statement.
Example
@echo off
SET str1 = String1
SET str2 = String2
if defined str1 echo "Variable str1 is defined"
if defined str3 (echo "Variable str3 is defined") else (echo "Variable str3 is not defined")
Output
Another special case for the ‘if’ statement is the "if exists ", which is used to test for the
existence of a file. Following is the general syntax of the statement.
Example
@echo off
if exist C:\set2.txt echo "File exists"
if exist C:\set3.txt (echo "File exists") else (echo "File does not exist")
Output
Let’s assume that there is a file called set2.txt in the C drive and that there is no file called
set3.txt. Then, following will be the output of the above code.
"File exists"
"File does not exist"
Advertisements
Sometimes, there is a requirement to have multiple ‘if’ statement embedded inside each
other. Following is the general form of this statement.
So only if condition1 and condition2 are met, will the code in the do_something block be
executed.
@echo off
SET /A a = 5
SET /A b = 10
if %a%==5 if %b%==10 echo "The value of the variables are correct"
Yet another special case is "if errorlevel", which is used to test the exit codes of the last
command that was run. Various commands issue integer exit codes to denote the status of
the command. Generally, commands pass 0 if the command was completed successfully and
1 if the command failed.
if errorlevel n somecommand
Generally, the execution of a batch file proceeds line-by-line with the command(s) on each
line being run in turn. However, it is often desirable to execute a particular section of a
batch file while skipping over other parts. The capability to hop to a particular section is
provided by the appropriately named "goto" command (written as one word). The target
section is labeled with a line at the beginning that has a name with a leading colon. Thus
the script looks like −
...
goto :label
...some commands
:label
...some other commands
Execution will skip over "some commands" and start with "some other commands". The
label can be a line anywhere in the script, including before the "goto" command. "Goto"
commands often occur in "if" statements. For example, you might have a command of the
type −
@echo off
SET /A a = 5
:labela
echo "The value of a is 5"
exit /b 0
:labelb
echo "The value of a is 10"
The code statements for the label should be on the next line after the declaration of
the label.
You can define multiple goto statements and their corresponding labels in a batch
file.
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 2 LEQ 3 will give true
the 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 3 GEQ 2 will give true
to the right operand
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.
Show Example
Operator Description
Batch Script language also provides assignment operators. Following are the assignment
operators available.
Show Example
Output will be 8
Output will be 2
Output will be 15
This divides the left operand with the right operand Set /A a = 6
and assigns the result to the left operand
/= a/ = 3
Output will be 2
Output will be 2
Bitwise operators are also possible in batch script. Following are the operators available.
Show Example
Operator Description
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
The date and time in DOS Scripting have the following two basic commands for retrieving
the date and time of the system.
DATE
@echo off
echo %DATE%
The current date will be displayed in the command prompt. For example,
Mon 12/28/2015
This command sets or displays the time.
TIME
@echo off
echo %TIME%
22:06:52.87
Following are some implementations which can be used to get the date and time in different
formats.
@echo off
echo/Today is: %year%-%month%-%day%
goto :EOF
setlocal ENABLEEXTENSIONS
set t = 2&if "%date%z" LSS "A" set t = 1
There are three universal “files” for keyboard input, printing text on the screen and printing
errors on the screen. The “Standard In” file, known as stdin, contains the input to the
program/script. The “Standard Out” file, known as stdout, is used to write output for
display on the screen. Finally, the “Standard Err” file, known as stderr, contains any error
messages for display on the screen.
Each of these three standard files, otherwise known as the standard streams, are referenced
using the numbers 0, 1, and 2. Stdin is file 0, stdout is file 1, and stderr is file 2.
One common practice in batch files is sending the output of a program to a log file. The >
operator sends, or redirects, stdout or stderr to another file. The following example shows
how this can be done.
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.
The pseudo file NUL is used to discard any output from a program. The following example
shows that the output of the command DIR is discarded by sending the output to NUL.
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.
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.
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
3221225794 The application failed to initialize properly. Indicates that the application has
been launched on a Desktop to which the current user has no access rights.
0xC0000142 Another possible cause is that either gdi32.dll or user32.dll has failed to
initialize.
-1073741502
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.
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.
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
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.
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.
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
Advertisements
The first part of the while implementation is to set the counters which will be used to control
the evaluation of the ‘if’ condition. We then define our label which will be used to embody
the entire code for the while loop implementation. The ‘if’ condition evaluates an expression.
If the expression evaluates to true, the code block is executed. If the condition evaluates to
false then the loop is exited. When the code block is executed, it will return back to the label
statement for execution again.
Following is the syntax of the general implementation of the while statement.
Set counters
:label
If (expression) (
Do_something
Increment counter
Go back to :label
)
The entire code for the while implementation is placed inside of a label.
The counter variables must be set or initialized before the while loop implementation
starts.
The expression for the while condition is done using the ‘if’ statement. If the
expression evaluates to true then the relevant code inside the ‘if’ loop is executed.
A counter needs to be properly incremented inside of ‘if’ statement so that the while
implementation can terminate at some point in time.
Finally, we will go back to our label so that we can evaluate our ‘if’ statement again.
@echo off
SET /A "index = 1"
SET /A "count = 5"
:while
if %index% leq %count% (
echo The value of index is %index%
SET /A "index = index + 1"
goto :while
)
In the above example, we are first initializing the value of an index integer variable to 1.
Then our condition in the ‘if’ loop is that we are evaluating the condition of the expression to
be that index should it be less than the value of the count variable. Till the value of index is
less than 5, we will print the value of index and then increment the value of index.
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.
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.
List – This will be the list of values for which the ‘for’ statement should be executed.
The do_something code block is what needs to be executed for each iteration for the
list of values.
@echo off
FOR %%F IN (1 2 3 4 5) DO echo %%F
The variable declaration is done with the %% sign at the beginning of the variable
name.
The do_something code is defined after the echo command. Thus for each value in
the list, the echo command will be executed.
1
2
3
4
5
Advertisements
The ‘for’ statement also has the ability to move through a range of values. Following is the
general form of the statement.
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.
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.
@ECHO OFF
FOR /L %%X IN (0,1,5) DO ECHO %%X
0
1
2
3
4
Advertisements
Following is the classic ‘for’ statement which is available in most programming languages.
for(variable declaration;expression;Increment) {
statement #1
statement #2
…
}
The Batch Script language does not have a direct ‘for’ statement which is similar to the
above syntax, but one can still do an implementation of the classic ‘for’ loop statement
using if statements and labels.
Set counter
:label
The entire code for the ‘for’ implementation is placed inside of a label.
The counters variables must be set or initialized before the ‘for’ loop implementation
starts.
The expression for the ‘for’ loop is done using the ‘if’ statement. If the expression
evaluates to be true then an exit is executed to come out of the loop.
A counter needs to be properly incremented inside of the ‘if’ statement so that the
‘for’ implementation can continue if the expression evaluation is false.
Finally, we will go back to our label so that we can evaluate our ‘if’ statement again.
Following is an example of how to carry out the implementation of the classic ‘for’ loop
statement.
@echo off
SET /A i = 1
:loop
The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
Advertisements
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.
The Batch Script language does not have a direct ‘for’ statement which does a break but this
can be implemented by using labels. The following diagram shows the diagrammatic
explanation of the break statement implementation in Batch Script.
The key thing to note about the above implementation is the involvement of two ‘if’
conditions. The second ‘if’ condition is used to control when the break is implemented. If the
second ‘if’ condition is evaluated to be true, then the code block is not executed and the
counter is directly implemented.
Following is an example of how to carry out the implementation of the break statement.
@echo off
SET /A "index=1"
SET /A "count=5"
:while
if %index% leq %count% (
if %index%==2 goto :Increment
echo The value of index is %index%
:Increment
SET /A "index=index + 1"
goto :while
)
The key thing to note about the above program is the addition of a label called :Increment.
When the value of index reaches 2, we want to skip the statement which echoes its value to
the command prompt and directly just increment the value of index.
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.
In Batch Script, a function is defined by using the label statement. When a function is newly
defined, it may take one or several values as input 'parameters' to the function, process the
functions in the main body, and pass back the values to the functions as output 'return
types'.
Every function has a function name, which describes the task that the function performs. To
use a function, you "call" that function with its name and pass its input values (known as
arguments) that matches the types of the function's parameters.
:function_name
Do_something
EXIT /B 0
The function_name is the name given to the function which should have some
meaning to match what the function actually does.
The EXIT statement is used to ensure that the function exits properly.
Calling a Function
1 A function is called in Batch Script by using the call command.
2 Functions can work with parameters by simply passing them when a call is made
to the function.
4 Local variables in functions can be used to avoid name conflicts and keep variable
changes local to the function.
Recursive Functions
File I/O
6 In Batch Script, it is possible to perform the normal file I/O operations that would
be expected in any programming language.
Creating Files
7 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.
Writing to Files
8 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.
Appending to Files
9 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.
Renaming Files
12 For renaming files, Batch Script provides the REN or RENAME command.
Moving Files
13 For moving files, Batch Script provides the MOVE command.
14 The pipe operator (|) takes the output (by default, STDOUT) of one command and
directs it into the input (by default, STDIN) of another command.
15 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.
16 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.
Folders
17 In Batch Script, it is possible to perform the normal folder based operations that
would be expected in any programming language.
Creating Folders
18 The creation of a folder is done with the assistance of the MD (Make directory)
command.
19 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.
Deleting Folders
20 For deleting folders, Batch Scripting provides the DEL command.
Renaming Folders
21 For renaming folders, Batch Script provides the REN or RENAME command.
Moving Folders
22 For moving folders, Batch Script provides the MOVE command.
Advertisements
A function is called in Batch Script by using the call command. Following is the syntax.
call :function_name
Following example shows how a function can be called from the main program.
@echo off
SETLOCAL
CALL :Display
EXIT /B %ERRORLEVEL%
:Display
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.
Functions can work with parameters by simply passing them when a call is made to the
function.
The parameters can then be accessed from within the function by using the tilde (~)
character along with the positional number of the parameter.
@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.
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
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.
@echo off
SETLOCAL
CALL :SetValue value1,value2
echo %value1%
echo %value2%
EXIT /B %ERRORLEVEL%
:SetValue
set "%~1 = 5"
set "%~2 = 10"
EXIT /B 0
5
10
Advertisements
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.
Localizing variables with SETLOCAL allows using variable names within a function freely
without worrying about name conflicts with variables used outside the function.
@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
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.
Outer
Outer
Advertisements
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.
The example shows how to calculate a Fibonacci number recursively. The recursion stops
when the Fibonacci algorism reaches a number greater or equal to a given input number.
The example starts with the numbers 0 and 1, the :myFibo function calls itself recursively to
calculate the next Fibonacci number until it finds the Fibonacci number greater or equal to
1000000000.
The first argument of the myFibo function is the name of the variable to store the output in.
This variable must be initialized to the Fibonacci number to start with and will be used as
current Fibonacci number when calling the function and will be set to the subsequent
Fibonacci number when the function returns.
@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"
In Batch Script, it is possible to perform the normal file I/O operations that would be
expected in any programming language.
Creating files
Reading files
Writing to files
Deleting files
Moving files
Renaming files
Advertisements
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. Following is a simple example of how to create a file
using the redirection command.
@echo off
echo "Hello">C:\new.txt
If the file new.txt is not present in C:\, then it will be created with the help of the above
command.
Advertisements
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. Following is a simple example of how to create a file
using the redirection command to write data to files.
@echo off
dir C:\>C:\new.txt
The above code snippet first uses the DIR command to get the directory listing of the entire
C:\ . It then takes that output and with the help of the redirection command sends it to the
file new.txt.
If you open up the file new.txt on your C drive, you will get the contents of your C drive in
this file. Following is a sample output.
Directory of C:\
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. Following is a simple example of how to
create a file using the redirection command to append data to files.
@echo off
echo "This is the directory listing of C:\ Drive">C:\new.txt
dir C:\>>C:\new.txt
In the above example, you can see that the first echo command is used to create the file
using the single redirection command whereas the DIR command is outputted to the file
using the double redirection filter.
If you open the file new.txt on your C drive, you will get the contents of your C drive in this
file plus the string “This is the directory listing of C:\ Drive” . Following is a sample output.
Directory of C:\
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. Since there is a no direct
command to read text from a file into a variable, the ‘for’ loop needs to be used to serve
this purpose.
@echo off
FOR /F "tokens=* delims=" %%x in (new.txt) DO echo %%x
The delims parameter is used to break up the text in the file into different tokens or words.
Each word or token is then stored in the variable x. For each word which is read from the
file, an echo is done to print the word to the console output.
If you consider the new.txt file which has been considered in previous examples, you might
get the following output when the above program is run.
Directory of C:\
Following are the description of the options which can be presented to the DEL command.
Names
1. Specifies a list of one or more files or directories. Wildcards may be used to delete
multiple files. If a directory is specified, all files within the directory will be deleted
/P
2.
Prompts for confirmation before deleting each file.
/F
3.
Force deletes of read-only files.
/S
4.
Deletes specified files from all subdirectories.
/Q
5.
Quiet mode, do not ask if ok to delete on global wildcard.
/A
6.
Selects files to delete based on attributes.
attributes
7.
R Read-only files, S System files, H Hidden files, A Files ready for archiving -
Prefix meaning not
del test.bat
The above command will delete the file test.bat in the current directory, if the file exists.
del c:\test.bat
The above command will delete the file C:\test.bat in the current directory, if the file exists.
del c:\*.bat
The * (asterisks) is a wild character. *.bat indicates that you would like to delete all bat files
in the c:\directory.
del c:\?est.tmp
The ? (question mark) is a single wild character for one letter. The use of this command in
the above example will delete any file ending with "est.tmp", such as pest.tmp or test.tmp.
Advertisements
For renaming files, Batch Script provides the REN or RENAME command.
The above command will rename all text files to files with .bak extension.
Following are the description of the options which can be presented to the DEL command.
[drive:][path]filename1
1.
Specifies the location and name of the file or files you want to move
destination
Specifies the new location of the file. Destination can consist of a drive letter and
2.
colon, a directory name, or a combination. If you are moving only one file, you
can also include a filename if you want to rename the file when you move it.
[drive:][path]dirname1
3.
Specifies the directory you want to rename.
dirname2
4.
Specifies the new name of the directory.
/Y
/-Y
6.
Causes prompting to confirm you want to overwrite an existing destination file.
Let’s look at some examples of renaming files.
The above command will move the files of c:\windows\temp to the temp directory in root.
The above command will move the files new.txt and test.txt into the c:\example folder.
Advertisements
The pipe operator (|) takes the output (by default, STDOUT) of one command and directs it
into the input (by default, STDIN) of another command. For example, the following
command sorts the contents of the directory C:\
In this example, both commands start simultaneously, but then the sort command pauses
until it receives the dir command's output. The sort command uses the dir command's
output as its input, and then sends its output to handle 1 (that is, STDOUT).
Following is another example of the pipe command. In this example, the contents of the file
C:\new.txt are sent to the sort command through the pipe filter.
@echo off
TYPE C:\new.txt | sort
Usually, the pipe operator is used along with the redirection operator to provide useful
functionality when it comes to working with pipe commands.
For example, the below command will first take all the files defined in C:\, then using the
pipe command, will find all the files with the .txt extension. It will then take this output and
print it to the file AllText.txt.
To use more than one filter in the same command, separate the filters with a pipe (|). For
example, the following command searches every directory on drive C:, finds the file names
that include the string "Log", and then displays them in one Command Prompt window at a
time −
Following are some examples of how the pipe filter can be used.
The following example send’s the list of all running tasks using the tasklist command and
sends the output to the find command. The find command will then find all processes which
are of the type notepad and display them in the command prompt.
The following example send’s the list of all running tasks using the tasklist command and
sends the output to the more command. The more command will then display the lists of
running tasks one page at a time.
tasklist | more
The following example send’s the list of all running tasks using the tasklist command and
sends the output to the find command. The find command will then find all processes which
are of the type notepad and then uses the redirection command to send the content to the
file tasklist.txt.
If you open the file tasklist.txt, you will get the following sample output.
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. The batch files parameters can
be recalled from within the program using the % operator along with the numeric position of
the parameter. Following is how the command line parameters are defined.
So on till %9.
Let’s take a look at a simple example of how command line parameters can be used.
@echo off
echo The first parameter is %1
echo The second parameter is %2
echo The third parameter is %3
If the above code is stored in a file called test.bat and the file is run as
test.bat 5 10 15
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.
@echo off
echo %1
echo %2
echo %3
echo %4
echo %5
echo %6
echo %7
echo %8
echo %9
echo %10
If the above code is stored in a file called test.bat and the file is run as
test.bat a b c d e f g h i j
a
b
c
d
e
f
h
i
a0
As you can see from the above output, the final value which should be shown as ‘j’ is being
shown as a0. This is because there is no parameter known as %10.
This limitation can be avoided by using the SHIFT operator. After your batch file handled its
first parameter(s) it could SHIFT them (just insert a line with only the command SHIFT),
resulting in %1 getting the value B, %2 getting the value C, etcetera, till %9, which now
gets the value J. Continue this process until at least %9 is empty.
Let’s look at an example of how to use the SHIFT operator to overcome the limitation of
command line arguments.
@ECHO OFF
:Loop
If the above code is stored in a file called test.bat and the file is run as
test.bat a b c d e f g h i j
a
b
c
d
e
f
h
i
j
Some characters in the command line are ignored by batch files, depending on the DOS
version, whether they are "escaped" or not, and often depending on their location in the
command line −
Commas (",") are replaced by spaces, unless they are part of a string in
doublequotes.
Semicolons (";") are replaced by spaces, unless they are part of a string in
doublequotes.
"=" characters are sometimes replaced by spaces, not if they are part of a string in
doublequotes.
The first forward slash ("/") is replaced by a space only if it immediately follows the
command, without a leading space.
Multiple spaces are replaced by a single space, unless they are part of a string in
doublequotes.
Leading spaces before the first command line argument are ignored.
Trailing spaces after the last command line argument are trimmed.
Advertisements
In Batch Script, it is possible to perform the normal folder based operations that would be
expected in any programming language.
Creating folders
Listing folders
Deleting folders
Renaming folders
Advertisements
The creation of a folder is done with the assistance of the MD (Make directory) command.
MKDIR [drive:]path
MD [drive:]path
md test
The above command will create a directory called test in your current directory.
md C:\test
The above command will create a directory called test in the C drive.
md “Test A”
If there are spaces in the folder name, then the folder name should be given in quotes.
mkdir \a\b\c
The above command creates directories recursively and is the same as issuing the following
set of commands.
mkdir \a
chdir \a
mkdir b
chdir b
mkdir c
Advertisements
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. The dir command also
shows the last modification date and time, as well as the file size.
[drive:][path][filename]
1.
Specifies drive, directory, or files to list
/A
2.
Displays files with specified attributes.
attributes
/B
4.
Uses bare format (no heading information or summary).
/C
5. Displays the thousand separator in file sizes. This is the default. Use /-C to disable
the display of the separator.
Let’s see some of the examples on how to use the DIR command.
dir *.exe
The above command lists any file that ends with the .exe file extension.
The above command uses multiple filespecs to list any files ending with .txt and .doc in one
command.
dir /ad
Lists only the directories in the current directory. If you need to move into one of the
directories listed use the cd command.
dir /s
Lists the files in the directory that you are in and all sub directories after that directory. If
you are at root "C:\>", type this command, this will list to you every file and directory on
the C: drive of the computer.
dir /p
If the directory has lots of files and you cannot read all the files as they scroll by, you can
use the above command and it displays all files one page at a time.
dir /w
If you don't need file information you can use the above command to list only the files and
directories going horizontally, taking as little space as needed.
dir /s /w /p
The above command will list all the files and directories in the current directory and the sub
directories, in wide format and one page at a time.
Advertisements
Following are the description of the options which can be presented to the DEL command.
Names
1. Specifies a list of one or more files or directories. Wildcards may be used to delete
multiple files. If a directory is specified, all files within the directory will be deleted
/P
2.
Prompts for confirmation before deleting each file.
/F
3.
Force deletes read-only files.
/S
4.
Deletes specified files from all subdirectories.
/Q
5.
Quiet mode, do not ask if ok to delete on global wildcard.
/A
6.
Selects files to delete based on attributes.
attributes
7.
R - Read-only files, S - System files, H - Hidden files, A - Files ready for archiving
- Prefix meaning not
Let’s look at some examples of how the DEL command can be used for folders.
del Example
The above command will delete the folder called Example in the current working directory.
del C:\Example
The above command will delete the folder called Example in C drive.
The above command will delete the folder called Example1 and Example2 in the current
working directory.
Advertisements
For renaming folders, Batch Script provides the REN or RENAME command.
The above command will rename the folder called Example in the current working directory
to Example1.
The above command will rename the folder called Example in C Drive to Example1.
Advertisements
Following are the description of the options which can be presented to the DEL command.
[drive:][path]filename1
1.
Specifies the location and name of the file or files you want to move
destination
Specifies the new location of the file. Destination can consist of a drive letter and
2.
colon, a directory name, or a combination. If you are moving only one file, you
can also include a filename if you want to rename the file when you move it.
[drive:][path]dirname1
3.
Specifies the directory you want to rename.
dirname2
4.
Specifies the new name of the directory.
/Y
/-Y
6.
Causes prompting to confirm you want to overwrite an existing destination file.
Let’s look at some examples of moving folders.
The above command will move all files from the current directory to the folder C:\Example.
The above command will move all files with the txt extension from the current directory to
the folder C:\Example.
The above command will move all files from the folder called ‘old’ in C drive to the folder
C:\Example.
In this chapter, we will discuss the various processes involved in Batch Script.
In Batch Script, the TASKLIST command can be used to get the list of currently running
processes within a system.
TASKLIST [/S system [/U username [/P [password]]]] [/M [module] | /SVC | /V] [/FI filter]
[/FO format] [/NH]
Following are the description of the options which can be presented to the TASKLIST
command.
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.
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.
Allows a user running Microsoft Windows XP professional, Windows 2003, or later to kill a
task from a Windows command line by process id (PID) or image name. The command used
for this purpose is the TASKILL command.
Following are the description of the options which can be presented to the TASKKILL
command.
DOS scripting also has the availability to start a new process altogether. This is achieved by
using the START command.
Wherein
Following are the description of the options which can be presented to the START
command.
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.
Aliases means creating shortcuts or keywords for existing commands. Suppose if we wanted
to execute the below command which is nothing but the directory listing command with the
/w option to not show all of the necessary details in a directory listing.
Dir /w
dw = dir /w
When we want to execute the dir /w command, we can simply type in the word dw. The
word ‘dw’ has now become an alias to the command Dir /w.
Alias are managed by using the doskey command.
Wherein
Following are the description of the options which can be presented to the DOSKEY
command.
/REINSTALL
1.
Installs a new copy of Doskey
/LISTSIZE = size
2.
Sets size of command history buffer.
/MACROS
3.
Displays all Doskey macros.
/MACROS:ALL
4.
Displays all Doskey macros for all executables which have Doskey macros.
/MACROS:exename
5.
Displays all Doskey macros for the given executable.
/HISTORY
6.
Displays all commands stored in memory.
/INSERT
7.
Specifies that new text you type is inserted in old text.
/OVERSTRIKE
8.
Specifies that new text overwrites old text.
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.
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.
An alias or macro can be deleted by setting the value of the macro to NULL.
@echo off
doskey cd = cd/test
doskey d = dir
d=
In the above example, we are first setting the macro d to d = dir. After which we are setting
it to NULL. Because we have set the value of d to NULL, the macro d will deleted.
An alias or macro can be replaced by setting the value of the macro to the new desired
value.
@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 now has an improved library which can be used in Batch Script for working with
devices attached to the system. This is known as the device console – DevCon.exe.
Windows driver developers and testers can use DevCon to verify that a driver is installed
and configured correctly, including the proper INF files, driver stack, driver files, and driver
package. You can also use the DevCon commands (enable, disable, install, start, stop, and
continue) in scripts to test the driver. DevCon is a command-line tool that performs device
management functions on local computers and remote computers.
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.
Hardware resources.
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.
Change the upper and lower filter drivers for a device setup class.
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
wherein
To list and display information about devices on the computer, use the following
commands −
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
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.
devcon status * > status.txt
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 is one of the key elements on a windows system. It contains a lot of
information on various aspects of the operating system. Almost all applications installed on
a windows system interact with the registry in some form or the other.
The Registry contains two basic elements: keys and values. Registry keys are container
objects similar to folders. Registry values are non-container objects similar to files. Keys
may contain values or further keys. Keys are referenced with a syntax similar to Windows'
path names, using backslashes to indicate levels of hierarchy.
This chapter looks at various functions such as querying values, adding, deleting and editing
values from the registry.
Reading from the registry is done via the REG QUERY command. This command can be used
to retrieve values of any key from within the registry.
Where RegKey is the key which needs to be searched for in the registry.
@echo off R
EG QUERY HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\
The above command will query all the keys and their respective values under the registry
key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\
The output will display all the keys and values under the registry key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\
This location in the registry has some key information about the windows system such as
the System Directory location.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows
Directory REG_EXPAND_SZ %SystemRoot%
SystemDirectory REG_EXPAND_SZ %SystemRoot%\system32
NoInteractiveServices REG_DWORD 0x1
CSDBuildNumber REG_DWORD 0x4000
ShellErrorMode REG_DWORD 0x1
ComponentizedBuild REG_DWORD 0x1
CSDVersion REG_DWORD 0x0
ErrorMode REG_DWORD 0x0
CSDReleaseType REG_DWORD 0x0
Advertisements
Adding to the registry is done via the REG ADD command. Note that in order to add values
to the registry you need to have sufficient privileges on the system to perform this
operation.
The REG ADD command has the following variations. In the second variation, no name is
specified for the key and it will add the name of “(Default)” for the key.
REG ADD [ROOT\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f]
REG ADD [ROOT\]RegKey /ve [/d Data] [/f]
Where
/t DataType − These are the data types defined as per the registry standards
which can be −
REG_SZ (default)
REG_DWORD
REG_EXPAND_SZ
REG_MULTI_SZ
@echo off
REG ADD HKEY_CURRENT_USER\Console /v Test /d "Test Data"
REG QUERY HKEY_CURRENT_USER\Console /v Test
In the above example, the first part is to add a key into the registry under the location
HKEY_CURRENT_USER\Console. This key will have a name of Test and the value assigned to
the key will be Test Data which will be of the default string type.
The second command just displays what was added to the registry by using the REG QUERY
command.
Following will be the output of the above program. The first line of the output shows that the
‘Add’ functionality was successful and the second output shows the inserted value into the
registry.
Deleting from the registry is done via the REG DEL command. Note that in order to delete
values from the registry you need to have sufficient privileges on the system to perform this
operation.
The REG DELETE command has the following variations. In the second variation, the default
value will be removed and in the last variation all the values under the specified key will be
removed.
Where
@echo off
REG DELETE HKEY_CURRENT_USER\Console /v Test /f
REG QUERY HKEY_CURRENT_USER\Console /v Test
In the above example, the first part is to delete a key into the registry under the location
HKEY_CURRENT_USER\Console. This key has the name of Test. The second command just
displays what was deleted to the registry by using the REG QUERY command. From this
command, we should expect an error, just to ensure that our key was in fact deleted.
Following will be the output of the above program. The first line of the output shows that the
‘Delete’ functionality was successful and the second output shows an error which was
expected to confirm that indeed our key was deleted from the registry.
Advertisements
Copying from the registry is done via the REG COPY command. Note that in order to copy
values from the registry, you need to have sufficient privileges on the system to perform
this operation on both the source location and the destination location.
@echo off
REG COPY HKEY_CURRENT_USER\Console HKEY_CURRENT_USER\Console\Test
REG QUERY HKEY_CURRENT_USER\Console\Test
In the above example, the first part is to copy the contents from the location
HKEY_CURRENT_USER\Console into the location HKEY_CURRENT_USER\Console\Test on the
same machine. The second command is used to query the new location to check if all the
values were copied properly.
Following is the output of the above program. The first line of the output shows that the
‘Copy’ functionality was successful and the second output shows the values in our copied
location.
Wherein Output − /od (only differences) /os (only matches) /oa (all) /on (no output).
@echo off
REG COMPARE HKEY_CURRENT_USER\Console HKEY_CURRENT_USER\Console\Test
The above program will compare all of the values between the registry keys
HKEY_CURRENT_USER\Console & HKEY_CURRENT_USER\Console\Test.
If there is a difference between the values in either registry key, it will be shown in the
output as shown in the following result. The following output shows that the value
‘EnableColorSelection’ is extra I the registry key ‘HKEY_CURRENT_USER\Console’.
View the current password & logon restrictions for the computer.
Wherein
FORCELOGOFF − Force the log-off of the current user within a defined time period.
MINPWLEN − This is the minimum password length setting to provide for the user.
MAXPWAGE − This is the maximum password age setting to provide for the user.
MINPWAGE − This is the minimum password age setting to provide for the user.
NET ACCOUNT
NET CONFIG
NET CONFIG
The above command will add the machine with the name dxbtest to the domain in which the
windows domain controller exists.
Advertisements
NET USER
The above command shows all the accounts defined on a system. Following is the output of
the above command.
The above command shows the details of Guest account defined on a system. Following is
the output of the above command.
The above command is used to stop the printer spooler service. Following is the output of
the above command.
The above command is used to start the printer spooler service. Following is the output of
the above command.
Sessions accepted 0
Sessions timed-out 0
Sessions errored-out 0
Kilobytes sent 0
Kilobytes received 0
System errors 0
Permission violations 0
Password violations 0
Files accessed 0
Communication devices accessed 0
Print jobs spooled 0
Advertisements
where
/USER − This needs to be specified to ensure that the right credentials are specified
when connecting to the network share.
The above command will connect to the share name \\computer\test and assign the Z: drive
name to it.
print c:\example.txt /c /d:lpt1
The above command will print the example.txt file to the parallel port lpt1.
As of Windows 2000, many, but not all, printer settings can be configured from Windows's
command line using PRINTUI.DLL and RUNDLL32.EXE
/F[file] − Location of an INF file that the INF file specified with /f may depend on.
/ii − Install printer using add printer wizard with an inf file.
/k − Print test page to specified printer, cannot be combined with command when
installing a printer.
There can be cases wherein you might be connected to a network printer instead of a local
printer. In such cases, it is always beneficial to check if a printer exists in the first place
before printing.
The existence of a printer can be evaluated with the help of the RUNDLL32.EXE
PRINTUI.DLL which is used to control most of the printer settings.
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.
Very often than not you can run into problems when running batch files and most often than
not you would need to debug your batch files in some way or the other to determine the
issue with the batch file itself. Following are some of the techniques that can help in
debugging Batch Script files.
Step 1 − REM out the @ECHO OFF line, i.e. REM @ECHO OFF or :: @ECHO OFF.
Step 2 − Run the batch file with the required command line parameters, redirecting all
output to a log file for later comparison.
test.bat > batch.log 2>&1
Step 4 − Check the previous line for any unexpected or invalid command, command line
switch(es) or value(s); pay special attention to the values of any environment variables
used in the command.
Step 5 − Correct the error and repeat this process until all error messages have
disappeared.
Another common source of errors are incorrectly redirected commands, like for example
"nested" FIND or FINDSTR commands with incorrect search strings, sometimes within a FOR
/F loop.
Step 1 − Insert "command check lines" just before a line which uses the complex command
set.
Following is an example wherein the ECHO command is inserted to mark where the output
of the first TYPE command ends and the next one starts.
TYPE %Temp%.\apipaorg.reg
ECHO.================================================ TYPE %Temp%.\apipaorg.reg
| FIND
"[HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\TCPIP\Parameters\Interfaces\"
Step 2 − Follow the procedure to find error message sources described above.
Step 3 − Pay special attention to the output of the "simplified" command lines: Is the
output of the expected format? Is the "token" value or position as expected?
Subroutines generating error messages pose an extra "challenge" in finding the cause of the
error, as they may be called multiple times in the same batch file.
To help find out what causes the incorrect call to the subroutine, follow these steps −
Step 1 − Add and reset a counter variable at the beginning of the script −
SET Counter = 0
Step 2 − Increment the counter each time the subroutine is called, by inserting the
following line at the beginning of the subroutine
SET /A Counter+=1
Step 3 − Insert another line right after the counter increment, containing only the SET
command; this will list all environment variables and their values.
Step 4 − Follow the procedure to find error message sources described above.
If you intend to distribute your batch files to other computers that may or may not run the
same Windows version, you will need to test your batch files in as many Windows versions
as possible.
The following example shows how to check for various operating system versions to check
the relevant windows versions.
@ECHO OFF
:: Check for Windows NT 4 and later
:DontRun
ECHO Sorry, this batch file was written for Windows XP and later versions only
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.
And you open the file testerrors.txt, you will see the following error.
The option /SERVER is unknown.
NET STATISTICS
[WORKSTATION | SERVER]
If you open the file called testlog.txt, it will show you a log of what commands were
executed.
ASSOC [.ext[=[Tipo_de_arquivo]]]
ATTRIB [+R | -R] [+A | -A ] [+S | -S] [+H | -H] [+I | -I]
[unidade:][caminho][arquivo] [/S [/D] [/L]]
+ Define um atributo.
- Limpa um atributo.
R Atributo de arquivo somente leitura.
A Atributo de arquivo morto.
S Atributo de arquivo do sistema.
H Atributo de arquivo oculto.
I Atributo de arquivo sem conte£do indexado.
X Sem atributo de arquivo de limpeza.
V Atributo de integridade.
[unidade:][caminho][arquivo]
Especifica um ou mais arquivos para processamento de atributos.
/S Processa os arquivos correspondentes na pasta atual
e em todas as subpastas.
/D Inclui pastas no processamento.
/L Trabalha nos atributos do Link Simb¢lico versus
o destino do Link Simb¢lico
BCDEDIT - Editor de Repositório de Dados de Configuração da Inicialização
bcdedit.exe /? /createstore
Para obter uma lista em ordem alfabética dos tópicos neste arquivo de
ajuda,
execute "bcdedit /? TOPICS".
Existe somente para manter a compatibilidade com sistemas DOS. Não tem
efeito
sob o Windows.
cd \winnt\profiles\username\programs\start menu
é o mesmo que:
cd "\winnt\profiles\username\programs\start menu"
CHCP [nnn]
Digite CHCP sem par僲etros para exibir o n ero da p爂ina de c igo ativa.
Exibe o nome da pasta ou altera a pasta atual.
cd \winnt\profiles\username\programs\start menu
é o mesmo que:
cd "\winnt\profiles\username\programs\start menu"
CLS
Inicia uma nova instância do interpretador de comando do Windows
CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON |
/V:OFF]
[[/S] [/C | /K] cadeia_de_caracteres]
- nenhuma opção /S
- exatamente duas aspas
- nenhum caractere especial entre as duas aspas,
onde o especial é um dos seguintes: &<>()@^|
- há um ou mais caracteres de espaço entre as
duas aspas
- a cadeia de caracteres entre as duas aspas é o nome
de um arquivo executável.
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
e/ou
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
HKEY_LOCAL_MACHINE\Software\Microsoft\Command
Processor\EnableExtensions
e/ou
HKEY_CURRENT_USER\Software\Microsoft\Command
Processor\EnableExtensions
DEL ou ERASE
COLOR
CD ou CHDIR
MD ou MKDIR
PROMPT
PUSHD
POPD
SET
SETLOCAL
ENDLOCAL
IF
FOR
CALL
SHIFT
GOTO
START (também inclui as alterações feitas na invocação de comando
externo)
ASSOC
FTYPE
HKEY_LOCAL_MACHINE\Software\Microsoft\Command
Processor\DelayedExpansion
e/ou
HKEY_CURRENT_USER\Software\Microsoft\Command
Processor\DelayedExpansion
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar
HKEY_LOCAL_MACHINE\Software\Microsoft\Command
Processor\PathCompletionChar
e/ou
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\CompletionChar
HKEY_CURRENT_USER\Software\Microsoft\Command
Processor\PathCompletionChar
COLOR [attr]
0 = Preto 8 = Cinza
1 = Azul 9 = Azul claro
2 = Verde A = Verde claro
3 = Verde-água B = Verde-água claro
4 = Vermelho C = Vermelho claro
5 = Roxo D = Lilás
6 = Amarelo E = Amarelo claro
7 = Branco F = Branco brilhante
COMPACT [/C | /U] [/S[:pasta]] [/A] [/I] [/F] [/Q] [arquivo [...]]
COPY [/D] [/V] [/N] [/Y | /-Y] [/Z] [/L] [/A | /B ] origem [/A | /B]
[+ origem [/A | /B] [+ ...]] [destino [/A | /B]]
Digite DATE sem parâmetros para exibir a data atual e poder digitar
a nova data. Pressione ENTER para manter a data inalterada.
[unidade:][caminho][nome_de_arquivo]
Especifica a unidade, o diretório e/ou arquivos a serem
listados.
Setas PARA CIMA e PARA BAIXO recuperam comandos; ESC limpa a linha de
comando;
F7 exibe o hist¢rico de comandos; ALT+F7 limpa o hist¢rico de comandos;
F8 pesquisa o hist¢rico de comandos;
F9 seleciona um comando por n£mero; ALT+F10 limpa as defini‡äes de
macros.
Lista de parâmetros:
/S sistema Especifica o sistema remoto ao qual se
conectar.
Exemplos:
DRIVERQUERY
DRIVERQUERY /FO CSV /SI
DRIVERQUERY /NH
DRIVERQUERY /S endereço_ip /U usuário /V
DRIVERQUERY /S sistema /U domínio\usuário /P senha /FO LIST
Exibe mensagens ou ativa ou desativa o eco de comando.
ENDLOCAL
FC [/A] [/C] [/L] [/LBn] [/N] [/OFF[LINE]] [/T] [/U] [/W] [/nnnn]
[unidade1:][caminho1]arquivo1 [unidade2:][caminho2]arquivo2
FC /B [unidade1:][caminho1]arquivo1 [unidade2:][caminho2]arquivo2
FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P]
[/F:arquivo] [/C:cadeia de caracteres] [/G:arquivo]
[/D:lista_de_pastas] [/A:atributos_de_cor] [/OFF[LINE]]
cadeia de caracteres [[unidade:][caminho]arquivo[ ...]]
Nos exemplos acima, %I e PATH podem ser substituídos por outros valores
válidos. A sintaxe %~ é terminada por um nome de variável FOR válido.
O uso de nomes de variáveis em maiúsculas como %I facilita a leitura e
evita confusão com os modificadores, que não fazem diferenciação entre
maiúsculas e minúsculas.
Formata um disco para ser utilizado com o Windows.
FTYPE [Tipo_de_arquivo[=[Cadeia_de_caracteres_do_comando_open]]]
Digite FTYPE sem parâmetros para exibir os tipos de arquivos atuais que
possuem cadeia de caracteres do comando open definidas. O FTYPE é
invocado com apenas um tipo de arquivo; ele exibe a cadeia de caracteres
do comando open atual para esse tipo de arquivo. Se nada for especificado
para a cadeia de caracteres do comando open, o comando FTYPE excluirá
a cadeia de caracteres do comando open para o tipo de arquivo. Dentro de
uma cadeia de caracteres do comando open, %0 ou %1 são substituídos
pelo nome de arquivo sendo iniciado por associação. %* obtém todos os
parâmetros e %2 obtém o primeiro parâmetro, %3 o segundo, etc. %~n
obtém todos os parâmetros restantes iniciados com o enésimo parâmetro,
onde
n pode estar entre 2 e 9, inclusive. Por exemplo:
ASSOC .pl=PerlScript
FTYPE PerlScript=perl.exe %1 %*
script.pl 1 2 3
defina PATHEXT=.pl;%PATHEXT%
script 1 2 3
Direciona o cmd.exe para uma linha com um rótulo em um programa em lotes.
GOTO rótulo
Você deve digitar um rótulo em uma linha iniciada com dois pontos (:).
Descrição:
Esta ferramenta de linha de comando exibe as informações do Conjunto
de Políticas Resultante (RSoP)
para um computador e um usuário de destino.
Lista de Parâmetros:
/S sistema Especifica o sistema remoto com o qual
será
estabelecida a conexão.
Exemplos:
GPRESULT /R
GPRESULT /H GPReport.html
GPRESULT /USER nome_usuário_destino /V
GPRESULT /S sistema /USER nome_usuário_destino /SCOPE COMPUTER /Z
GPRESULT /S sistema /U nome_usuário /P senha /SCOPE USER /V
Fornece informações de ajuda sobre comandos do Windows.
HELP [comando]
Observa‡Æo:
As SIDs podem estar no formato num‚rico ou de nome amig vel. Se for
usado o formato num‚rico, afixe um * ao in¡cio da SID.
Exemplos:
A cláusula ELSE deve ocorrer na mesma linha que o comando após o IF. Por
exemplo:
IF EXIST nome_de_arquivo. (
del nome_de_arquivo.
) ELSE (
echo nome_de_arquivo. ausente.
)
EQU - igual
NEQ - diferente
LSS - menor que
LEQ - menor que ou igual
GTR - maior que
GEQ - maior que ou igual
goto resposta%ERRORLEVEL%
:resposta0
echo O programa retornou o código 0
:resposta1
echo O programa retornou o código 1.
LABEL [unidade:][r¢tulo]
LABEL [/MP] [volume] [r¢tulo]
MKDIR [unidade:]caminho
MD [unidade:]caminho
mkdir \a\b\c\d
mkdir \a
chdir \a
mkdir b
chdir b
mkdir c
chdir c
mkdir d
MKDIR [unidade:]caminho
MD [unidade:]caminho
mkdir \a\b\c\d
mkdir \a
chdir \a
mkdir b
chdir b
mkdir c
chdir c
mkdir d
Descrição:
Permite que um administrador liste ou desconecte arquivos e pastas
que foram abertos em um sistema.
Lista de parâmetros:
/Disconnect Desconecta um ou mais arquivos abertos.
Exemplos:
OPENFILES /Disconnect /?
OPENFILES /Query /?
OPENFILES /Local /?
Exibe ou define um caminho de pesquisa para arquivos executáveis.
PATH [[unidade:]caminho[;...][;%PATH%]
PATH ;
POPD
PROMPT [texto]
RECOVER [unidade:][caminho]arquivo
Consulte a referˆncia aos comandos online na Ajuda do Windows
antes de usar o comando RECOVER.
Registra comentários em um arquivo em lotes ou no CONFIG.SYS.
REM [comentário]
Renomeia um ou mais arquivos.
Note que você não pode especificar uma nova unidade ou caminho para o
arquivo de destino.
Renomeia um ou mais arquivos.
Note que você não pode especificar uma nova unidade ou caminho para o
arquivo de destino.
Substitui arquivos.
::
:: Opções de cópia :
::
/S :: copiar subdiretórios, mas não os vazios.
/E :: copiar subdiretórios, incluindo os vazios.
/LEV:n :: copiar somente os níveis superiores da
árvore
de diretórios de origem.
::
:: Opções de Seleção de Arquivo :
::
/A :: copiar somente os arquivos com o conjunto de
atributos de Arquivamento.
/M :: copiar somente os arquivos com o atributo de
Arquivamento e redefini-los.
/IA:[RASHCNETO] :: Incluir somente arquivos com qualquer um dos
conjuntos determinados de Atributos.
/XA:[RASHCNETO] :: eXcluir arquivos com qualquer um dos
conjuntos
determinados de Atributos.
::
:: Opções de Repetição :
::
/R:n :: número de Repetições em cópias com falhas:
o padrão é 1 milhão.
/W:n :: tempo de espera entre as repetições: o
padrão
é 30 segundos.
::
:: Opções de Log :
::
/L :: Listar somente - não copiar, usar carimbo de
data/hora ou excluir qualquer arquivo.
/X :: relatar todos os arquivos eXtra, não apenas
os
selecionados.
/V :: produzir saída detalhada, mostrando arquivos
ignorados.
/TS :: incluir carimbo de data/hora no arquivo de
origem na saída.
/FP :: incluir nome de caminho completo de arquivos
na
saída.
/BYTES :: Imprimir tamanhos como bytes.
::
:: Opções de Trabalho :
::
/JOB:trabalho :: pegar parâmetros do arquivo de trabalho
nomeado.
/SAVE:trabalho :: salvar parâmetros no arquivo de trabalho
nomeado
/QUIT :: sair depois de processar a linha de
comando (para exibir parâmetros).
/NOSD :: nenhum diretório de origem especificado.
/NODD :: nenhum diretório de destino especificado.
/IF :: incluir os seguintes arquivos.
::
:: Comentários :
::
O uso de /PURGE ou /MIR no diretório raiz do volume
fará robocopy aplicar a operação solicitada também nos arquivos do
diretório Informações do Volume do Sistema. Se isso não for
desejado, a opção /XD poderá ser usada como instrução para
robocopy
ignorar esse diretório.
SCHTASKS /parameter [argumentos]
Descrição:
Permite que um administrador crie, exclua, consulte, altere, execute
e
termine tarefas agendadas em um sistema local ou remoto.
Lista de parâmetros:
/Create Cria uma nova tarefa agendada.
Examples:
SCHTASKS
SCHTASKS /?
SCHTASKS /Run /?
SCHTASKS /End /?
SCHTASKS /Create /?
SCHTASKS /Delete /?
SCHTASKS /Query /?
SCHTASKS /Change /?
SCHTASKS /ShowSid /?
Exibe, define ou remove variáveis de ambiente do cmd.exe.
SET [variável=[cadeia_de_caracteres]]
SET P
O comando SET não permitirá que um sinal de igual seja parte do nome de
uma variável.
SET /A expressão
SET /P variável=[cadeia_do_prompt]
() - agrupamento
! ~ - - operadores unários
* / % - operadores aritméticos
+ - - operadores aritméticos
<< >> - alternância lógica
& - bit a bit E
^ - bit a bit exclusivo OU
| - bit a bit OU
= *= /= %= += -= - atribuição
&= ^= |= <<= >>=
, - separador de expressões
%PATH:seq1=seq2%
%PATH:~10,5%
%PATH:~-10%
%PATH:~0,-2%
set VAR=antes
if "%VAR%" == "antes" (
set VAR=depois
if "%VAR%" == "depois" @echo Se você ler isto, terá funcionado
)
set LIST=
for %i in (*) do set LIST=%LIST% %i
echo %LIST%
set VAR=antes
if "%VAR%" == "antes" (
set VAR=depois
if "!VAR!" == "depois" @echo Se você ler isto, terá funcionado
)
set LIST=
for %i in (*) do set LIST=!LIST! %i
echo %LIST%
%DATE% - expande para a data atual usando o mesmo formato que o comando
DATE.
%TIME% - expande para a hora atual usando o mesmo formato que o comando
TIME.
SETLOCAL
Isso funciona porque nas versões mais antigas do CMD.EXE, SETLOCAL NÃO
define o valor ERRORLEVEL. O comando VERIFY com um argumento
incorreto inicializa o valor ERRORLEVEL para um valor diferente de zero.
Altera a posição dos parâmetros substituíveis em um arquivo em lotes.
SHIFT [/n]
SHIFT /2
Esses dois processos podem ser ainda mais restringidos para executar em
processadores específicos dentro do mesmo nó NUMA. No exemplo a seguir,
application1 é executado nos dois processadores de ordem inferior do nó,
enquanto application2 é executado nos próximos dois processadores do nó.
Esse
exemplo presume que o nó especificado tem no mínimo quatro processadores
lógicos.Observe que o número do nó pode ser alterado para qualquer número
de nó
válido para aquele computador sem precisar alterar a máscara de
afinidade.
Ao executar uma linha de comando cujo primeiro token NÃO contenha uma
extensão, o CMD.EXE usará o valor da variável de ambiente PATHEXT
para determinar quais extensões serão procuradas e em que ordem.
O valor padrão da variável PATHEXT é:
.COM;.EXE;.BAT;.CMD
Digite SUBST sem parƒmetros para exibir a lista das unidades virtuais
atuais.
SYSTEMINFO [/S sistema [/U usuário [/P [senha]]]] [/FO formato] [/NH]
Descrição:
Esta ferramenta exibe informações de configuração de sistema para
um computador local ou remoto, inclusive níveis de service pack.
Lista de parâmetros:
/S system Especifica o sistema remoto ao qual
se conectar.
Exemplos:
SYSTEMINFO
SYSTEMINFO /?
SYSTEMINFO /S sistema
SYSTEMINFO /S sistema /U usuário
SYSTEMINFO /S sistema /U domínio\usuário /P senha /FO TABLE
SYSTEMINFO /S sistema /FO LIST
SYSTEMINFO /S sistema /FO CSV /NH
TASKKILL [/S sistema [/U usuário [/P [senha]]]]
{ [/FI filtro] [/PID processid | /IM imagename] } [/T] [/F]
Descrição:
Esta ferramenta é usada para finalizar tarefas por identificação de
processo (PID) ou nome de imagem.
Lista de parâmetros:
/S system Especifica o sistema remoto ao qual se
conectar.
Filtro(s):
Nome do filtro Operadores válidos Valor(es) válido(s)
-------------- ------------------ -----------------------------
-
STATUS eq, ne EM EXECUÇÃO |
NÃO RESPONDENDO |
DESCONHECIDO
IMAGENAME eq, ne Qualquer nome de imagem.
PID eq, ne, gt, lt, ge, le Valor de PID.
SESSION eq, ne, gt, lt, ge, le Número de sessão.
CPUTIME eq, ne, gt, lt, ge, le Horário de CPU no formato
de hh:mm:ss.
hh - horas,
mm - minutos, ss - segundos
MEMUSAGE eq, ne, gt, lt, ge, le Uso de memória em KB.
USERNAME eq, ne Nome de usuário em formato
[domínio\]usuário
MODULES eq, ne Nome da DLL
SERVICES eq, ne Nome de serviço
WINDOWTITLE eq, ne Título de janela
OBS.
----
1) O caractere curinga '*' para a chave /IM é aceito somente quando
um
filtro é aplicado.
2) O encerramento de processos remotos sempre é forçado (/F).
3) os filtros "WINDOWTITLE" e "STATUS" não são considerados quando um
computador remoto é especificado.
Exemplos:
TASKKILL /IM notepad.exe
TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
TASKKILL /F /IM cmd.exe /T
TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"
TASKKILL /F /FI "USERNAME eq NT AUTHORITY\SYSTEM" /IM notepad.exe
TASKKILL /S sistema /U domínio\usuário /FI "USERNAME ne NT*" /IM *
TASKKILL /S sistema /U usuário /P senha /FI "IMAGENAME eq note*"
TASKLIST [/S sistema [/U nome_usuário [/P [senha]]]]
[/M [módulo] | /SVC | /V] [/FI filtro] [/FO formato] [/NH]
Descrição:
Esta ferramenta exibe uma lista de aplicativos em execução no momento
em
um computador local ou remoto.
Lista de parâmetros:
/S sistema Especifica o sistema remoto ao qual se
conectar.
Filtros:
Nome do Filtro Operadores Válidos Valor(es) Válido(s)
----------- --------------- --------------------------
STATUS eq, ne EMEXECUÇÃO | SUSPENSO
NÃO RESPONDE | DESCONHECIDO
IMAGENAME eq, ne Nome da imagem
PID eq, ne, gt, lt, ge, le Valor do PID
SESSION eq, ne, gt, lt, ge, le Número da sessão
SESSIONNAME eq, ne Nome da sessão
CPUTIME eq, ne, gt, lt, ge, le Tempo de CPU no formato
de hh:mm:ss.
hh - horas,
mm - minutos, ss - segundos
MEMUSAGE eq, ne, gt, lt, ge, le Uso da memória em KB
USERNAME eq, ne Nome de usuário no formato
[domínio\]usuário
SERVICES eq, ne Nome do serviço
WINDOWTITLE eq, ne Título da janela
MODULES eq, ne DLL name
Examples:
TASKLIST
TASKLIST /M
TASKLIST /V /FO CSV
TASKLIST /SVC /FO LIST
TASKLIST /APPS /FI "STATUS eq EM EXECUÇÃO"
TASKLIST /M wbem*
TASKLIST /S sistema /FO LISTA
TASKLIST /S sistema /U domínio\nomedeusuário /FO CSV /NH
TASKLIST /S sistema /U nomedeusuário /P senha /FO TABELA /NH
TASKLIST /FI "NOMEDEUSUÁRIO ne AUTORIDADE NT\SISTEMA" /FI "STATUS eq
em execução"
Exibe ou define a hora do sistema.
TYPE [unidade:][caminho]nomedearquivo
Exibe a versão do Windows.
VER
Faz com que o cmd.exe verifique ou não se seus arquivos foram gravados
corretamente no disco.
VOL [unidade:]
[op‡äes globais] <comando>
XCOPY origem [destino] [/A | /M] [/D[:data]] [/P] [/S [/E]] [/V] [/W]
[/C] [/I] [/Q] [/F] [/L] [/G] [/H] [/R] [/T]
[/U]
[/K] [/N] [/O] [/X] [/Y] [/-Y] [/Z] [/B] [/J]
[/EXCLUDE:arquivo1[+arquivo2][+arquivo3]...]