0% found this document useful (0 votes)
504 views31 pages

Windows Batch Scripting

This document summarizes key aspects of using the Windows command interpreter (cmd.exe): - Command lines are parsed, with variables substituted and special characters handled. Commands can be combined into pipelines and compound commands using syntax rules. - Redirection specifies where command output is sent. Common redirects include > to overwrite a file, >> to append, and 2> to send errors elsewhere. - Environment variables affect command interpreter operation. Important ones include COMSPEC (command interpreter path) and PATH (locations of external commands).

Uploaded by

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

Windows Batch Scripting

This document summarizes key aspects of using the Windows command interpreter (cmd.exe): - Command lines are parsed, with variables substituted and special characters handled. Commands can be combined into pipelines and compound commands using syntax rules. - Redirection specifies where command output is sent. Common redirects include > to overwrite a file, >> to append, and 2> to send errors elsewhere. - Environment variables affect command interpreter operation. Important ones include COMSPEC (command interpreter path) and PATH (locations of external commands).

Uploaded by

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

Windows Batch Scripting

This book describes the Microsoft-supplied command inwith the contents of those variables.
terpreter on Windows NT, Windows XP, Windows Vista,
Quoting Special characters can be quoted, to remove
Windows 7 and later, which is cmd.exe.
their special meanings.

Syntax Command lines are developed into a sequence


of commands according to a syntax.

Introduction

This book addresses 32-bit Windows commands appli- Redirection Redirection specications are applied, and
cable to modern versions of Windows based on the Winremoved from the command line, before an individdows NT environment. It does not address commands
ual command in a sequence is executed.
that are specic to DOS environments and to DOS-based
operating systems, such as Windows 95, Windows 98,
and Windows Me, whose Microsoft-supplied command 2.1.1 Variable substitution
interpreters are in fact DOS programs, not Win32 programs.
Command lines can contain variable specications.
You can nd out which version of cmd.exe you are run- These comprise a % character followed by a name. The
name is ended by a second % character, except in special
ning using the VER command.
cases such as the batch le parameters %1, %2, and so
This book rst describes using the Windows NT com- forth.
mand interpreter, how it receives, parses, and processes
commands from users. Then it describes various com- Variable specications are replaced with values. The
value used to replace a variable specication is as follows:
mands available.
To nd a list of all MS-DOS commands and a denition
for all of them, open the command prompt on all Microsoft/Windows computers, and type help. To nd out
about a particular command, type the name of the command followed by "/?".

For variable specication names that match the


names of environment variables, the replacement is
the value of the named environment variable. For
example: %PATH% is replaced by the value of the
PATH environment variable.

The subject of this book is also known as batch programming, even though batch refers not only to batch les
for MS DOS and Windows command interpreter. Other
subject terms include batch le programming, batch
le scripting, Windows batch command, Windows
batch le, Windows command line, Windows command prompt, and Windows shell scripting.

2
2.1

For variable specications that name batch le parameters (i.e. that are non-negative decimal numbers), the replacement is the value of the parameter
taken from the arguments with which the batch le
was invoked (subject to any subsequent modications by the SHIFT command). For example: %2
is replaced by the value of the second batch le parameter.

Using the Windows command interpreter

Special names Some variable names are not visible using SET command. Rather, they are made available for
reading using the % notation. To nd out about them,
type help set.

How a command line is interpreted

The parsing of a command line into a sequence of comSpecial variable names and what they expand to:
mands is complex, and varies subtly from command interpreter to command interpreter. There are, however, Links:
four main components:
Windows Environment Variables at ss64.com

Variable substitution A command line is scanned for


variable specications, and any found are replaced

Command shell overview at Microsoft


1

2 USING THE WINDOWS COMMAND INTERPRETER

2.1.2

Quoting

one after the other, and the conjunction controls whether


the command interpreter executes the next pipeline or
To prevent the metacharacters that control command syn- not. An example of a compound command (compristax and redirection from having their special meanings, ing two pipelines, which themselves are just simple comquoting is used. This takes two forms:
mands) is move le.txt le.bak && dir > le.txt.
The conjunctions are:
Although they don't process quotation marks, in
command arguments, specially themselves, but simply pass them along as-is to the commands ex- & The simplest conjunction. The next pipeline is always
executed after the current one has completed exeecuted, command interpreters do recognise when
cuting.
quotation marks (") surround metacharacters. The
& metacharacter does not have its usual eect on
&& A positive conditional conjunction. The next
command syntax if it is within a pair of quotation
pipeline is executed if the current one completes exmarks.
ecuting with a zero exit status.
e.g. The command line echo "&" will
|| A negative conditional conjunction. The next pipeline
invoke the ECHO command passing it
is executed if the current one completes executing
the three characters "&" as its command
with a non-zero exit status.
tail, rather than split the command line in
twain at the & character as would occur
if the character were not within quotaA parenthesized command is a compound command ention marks.
closed in parentheses (i.e. ( and )). From the point of
view of syntax, this turns a compound command into a
The escape character (always a ^ in Microsofts
simple command, whose overall output can be redirected.
CMD) used in front of a metacharacter also prevents
that metacharacter from having its usual eect on For example: The command line ( pushd temp & dir &
command syntax. The escape character itself is popd ) > somele causes the standard output of the entire
stripped from the command line before it is passed compound command ( pushd temp & dir & popd ) to be
redirected to somele.
to the command actually being invoked.
e.g. The command line echo ^& will invoke the ECHO command passing it the
character & as its command tail, rather
than split the command line in twain at
the & character as would otherwise occur.

2.1.4 Redirection

Redirection specications are applied, and removed from


the command line, before an individual command in a
sequence is executed. Redirection specications control
where the standard input, standard output, and standard
error le handles for a simple command point. They over2.1.3 Syntax
ride any eects to those le handles that may have resulted from pipelining. (See the preceding section on
Command lines are developed into a sequence of comcommand syntax.) Redirection signs > and >> can be
mands according to a syntax. In that syntax, simple comprexed with 1 for the standard output (same as no premands may be combined to form pipelines, which may in
x) or 2 for the standard error.
turn be combined to form compound commands, which
The redirection specications are:
nally may be turned into parenthesized commands.
A simple command is just a command name, a command
tail, and some redirection specications. An example of < lename Redirect standard input to read from the
named le.
a simple command is dir *.txt > somele.
A pipeline is several simple commands joined together > lename Redirect standard output to write to the
with the pipe metacharacter"|", also known as the
named le, overwriting its previous contents.
vertical bar. The standard output of the simple command preceding each vertical bar is connected to the stan- >> lename Redirect standard output to write to the
named le, appending to the end of its previous condard input of the simple command following it, via a
tents.
pipe. The command interpreter runs all of the simple
commands in the pipeline in parallel. An example of a
pipeline (comprising two simple commands) is dir *.txt | >&h Redirect to handle h, where handle is any of 0
standard input, 1standard output, 2standard ermore.
ror, and more.
A compound command is a set of pipelines separated by
conjunctions. The pipelines are executed sequentially, <&h Redirect from handle h.

2.4

Environment variables

Examples:
dir *.txt >listing.log
Redirects the output of the dir command to
listing.log le.
dir *.txt 2>NUL
Redirects errors of the dir command to
nowhere.
dir *.txt >listing.log 2>&1
Redirects the output of the dir command to
listing.log le, along with the error messages.

2.4 Environment variables


The environment variables of the command interpreter
process are inherited by the processes of any (external)
commands that it executes. A few environment variables
are used by the command interpreter itself. Changing
them changes its operation.
Environment variables are aected by the SET, PATH,
and PROMPT commands.
To unset a variable, set it to empty string, such as set
myvar=".
The command interpreter inherits its initial set of environment variables from the process that created it. In
the case of command interpreters invoked from desktop
shortcuts this will be Windows Explorer, for example.

Command interpreters generally have textual user interfaces, not graphical ones, and so do not recognize the
Redirects the output of the dir command Windows message that informs applications that the ento listing.log le, and the error messages to vironment variable template in the Registry has been
changed. Changing the environment variables in Conlisting-errors.log le.
trol Panel will cause Windows Explorer to update its own
environment variables from the template in the Registry,
Links:
and thus change the environment variables that any subsequently invoked command interpreters will inherit. However, it will not cause command interpreters that are al Redirection at ss64.com
ready running to update their environment variables from
Using command redirection operators at Microsoft the template in the Registry.
dir *.txt >listing.log 2>listing-errors.log

2.2

How a command is executed

(...)

2.3

Batch reloading

2.4.1 COMSPEC
The COMSPEC environment variable contains the full
pathname of the command interpreter program le. This
is just inherited from the parent process, and is thus indirectly derived from the setting of COMSPEC in the environment variable template in the Registry.

The command interpreter reloads the content of a batch


2.4.2 PATH
after each execution of a line or a bracketed group.
If you start the following batch and change echo A to The value of the PATH environment variable comprises
echo B in the batch shortly after starting it, the output a list of directory names, separated by semi-colon charwill be B.
acters. This is the list of directories that are searched,
@echo o ping -n 6 127.0.0.1 >nul & REM wait echo A in order, when locating the program le of an external
command to execute.
What is on a single line does matter; changing echo A
in the following batch after running it has no impact:
2.4.3 PATHEXT
@echo o ping -n 6 127.0.0.1 >nul & echo A
Nor have after-start changes have any impact on com- The value of the PATHEXT environment variable commands bracketed with ( and ). Thus, changing echo A prises a list of lename extensions, separated by semicolon characters. This is the list of lename extensions
after starting the following batch has no impact:
that are applied, in order, when locating the program le
@echo o for /L %%i in (1,1,10) do ( echo A ping -n 2
of an external command to execute.
127.0.0.1 >nul & REM wait )
An example content of PATHEXT printed by echo
Ditto for any other enclosing, including this one:
%PATHEXT%":
@echo o ( ping -n 6 127.0.0.1 >nul & REM wait echo
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
A)

2 USING THE WINDOWS COMMAND INTERPRETER

By adding ".PL to the variable, you can ensure Perl pro- Examples:
grams get run from the command line even when typed
without the ".pl extension. Thus, instead of typing my dir /?
di.pl a.txt b.txt, you can type mydi a.txt b.txt.
Displays the help. This option is provided by
Adding ".PL to the variable in Windows Vista and later:
many commands.
setx PATHEXT %PATHEXT%;.PL
If you use set available in Windows XP, the
eect will be temporary and impacting only
the current console or process.
Links:
Windows Environment Variables at ss64
Making Python scripts run on Windows without
specifying .py extension at stackoverow
2.4.4

PROMPT

The PROMPT environment variable controls the text


emitted when the command interpreter displays the
prompt. The command interpreter displays the prompt
when prompting for a new command line in interactive
mode, or when echoing a batch le line in batch le mode.
Various special character sequences in the value of the
PROMPT environment variable cause various special effects when the prompt is displayed, as in the following
table:
Links:
prompt at ss64
prompt at Microsoft

2.5

Switches

Most Windows commands provide switches AKA options to direct their behavior.
Observations:
Switches most often consist of a single-letter; some
switches consist of a sequence of multiple letters.
Switches are preceded with a slash (/) rather than, as
in some other operating systems, with a minus sign
(-).
Switches are case-insensitive rather than, as in some
other operating systems, case-sensitive.
If a command from another operating system is
ported to Windows (such as grep), it usually retains
the option conventions from the original operating
system, including the use of minus sign and casesensitivity.

dir /b /s
Lists all les and folders in the current folder
recursively. Two switches are used: b and s.
dir /bs
Does not work; switches cannot be accumulated behind a single slash.
ndstr /ric:"id: *[0-9]*" File.txt
Unlike many other commands, ndstr allows
the accumulation of switches behind a single slash. Indeed, r, i and c are single-letter
switches.
dir/b/s
Works. In dir, removing whitespace between
the command and the rst switch or between
the switches does not make a dierence; thus,
does the same as dir /b /s.
tree/f/a
Does not work, unlike tree /f /a. In tree, separation by whitespace is mandatory. Nor does
nd/i/v work.
dir /od
The switch letter o is further modied by a single letter specifying that ordering should be by
date. The letter d is not a switch by itself. Similar cases include dir /ad and more /t4.
dir /B /S
The switches are case-insensitive, unlike in
some other operating systems.
sort /r le.txt
Sorts the le in a reverse order.
sort /reverse le.txt
Sort allows the switch string to be longer than
a single-letter.
sort /reve le.txt
Sort allows the specied switch string to be
a substring of the complete long name of the
switch. Thus, does the same as the above.
sort /reva le.txt

2.6

Error level
Does not work, since reva is not a substring
of reverse.

taskkill /im AcroRd32.exe


Taskkill requires a multiletter switch name for
/im; shortening to /i does not work.
java -version
Java, which originated in the environment of
another operating system family, uses the minus convention for its switches AKA options.

5
echo %ERRORLEVEL%
Displays the error level without changing it.
if %errorlevel% equ 0 echo The error level is zero,
meaning success.
if %errorlevel% neq 0 echo The error level is nonzero, meaning failure.
if errorlevel 1 echo The error level is >= 1, meaning
failure via positive error level.
Does not cover failure via negative error level.
Note the ">=" part: this is not the same as if
%errorlevel% equ 1.

grep --help
If GNU grep is installed, it requires multiletter switches to be preceded by two dashes.

2.6

Error level

Commands usually set error level at the end of their execution. In Windows NT and later, it is a 32-bit signed
integer; in MS DOS, it used to be an integer from 0 to
255. Keywords: return code, exit code, exit status.
The conventional meaning of the error level:

exit /b 1
Returns a batch le, setting the error level to
1.
cmd /c exit /b 10
In the middle of a batch le or on the command
line, sets the error level to 10.
(cmd /c exit /b 0 && Echo Success) & (cmd /c
exit /b 1 || Echo Failure)
As above, showing the error level is indeed affected.

0 - success
not 0 - failure
The error levels being set are usually positive.
If the command does not distinguish various kinds
of failure, the error level on failure is usually 1.
Uses of the error level:

(cmd /c exit /b 0 & cmd /c exit /b 1) || Echo


Failure
The error level of a chain created by & is the
error level of the last command of the chain.
cmd /c exit /b 1 & if not errorlevel 1 echo
Would-be success
The if not errorlevel 1 test, which might appear to test for success, passes on negative
numbers: it tests on not error level >= 1,
which is error level <= 0.

It can be tested using && and ||; see also #Syntax.


It can be tested using IF.
The value can be accessed from ERRORLEVEL
variable.
Examples:

set myerrorlevel=%errorlevel%
Remembers the error level for later.
set errorlevel=0
To be avoided: overshadows the built-in errorlevel variable. Ensures that subsequent accesses via %ERRORLEVEL% return 0 rather
than the actual error level.

dir >NUL && echo Success


The part after && is executed only if the error
level is zero.
color 00 || echo Failure
The part after || is executed only if the error
level is non-zero, whether positive or negative.
color 00 || (
echo Failure
)
Multiline bracketing works as well.

cmd /c exit /b 0
if 1 equ 1 ( cmd /c exit /b 1 & echo %errorlevel%
)
Displays 0, since %errorlevel% gets expanded
before cmd /c exit /b 1 gets executed.
Links:
Error level at ss64

2 USING THE WINDOWS COMMAND INTERPRETER

2.7

String processing

Getting a substring of a variable by position and length:


Before running the following examples, ensure that %a%
equals abcd by running this:
set a=abcd
The examples:
echo %a:~0,1%
Result: a
echo %a:~1,1%
Result: b
echo %a:~0,2%
Result: ab
echo %a:~1,2%
Result: bc
echo %a:~1%
Result: bcd
echo %a:~1%
Result: d
echo %a:~2%
Result: cd
echo %a:~0,2%
Result: ab

if %a:~0,1%==a echo yes


If variable a starts with a, echo yes.
if %a:~0,2%==ab echo yes
If variable a starts with ab, echo yes.
String replacement:
set a=abcd & echo %a:c=%
Result: abd
set a=abcd & echo %a:c=e%
Result: abed
set a=abcd & echo %a:*c=%
Result: d
The asterisk only works at the beginning of the
sought pattern; it does not work at the end or
in the middle.
See also the help for SET command: set /?.
Splitting a string by any of " ", ",, and ";":
set myvar=a b,c;d
for %%a in (%myvar%) do echo %%a
Splitting a string by semicolon, assuming the string contains no quotation marks:
@echo o set myvar=a b;c;d set strippedvar=%myvar%
:repeat for /f delims=;" %%a in ("%strippedvar%")
do echo %%a set prestrippedvar=%strippedvar% set
strippedvar=%strippedvar:*;=% if not "%prestrippedvar:;=%"=="%prestrippedvar%" goto :repeat

echo %a:~0,1%
Result: abc
echo %a:~1,1%
Result: bc
Testing substring containment:

2.8 Command-line arguments


The command-line arguments AKA command-line parameters passed to a batch script are accessible as %1,
%2, ..., %9. There can be more than nine arguments; to
access them, see how to loop over all of them below.
The syntax %0 does not refer to a command-line argument but rather to the name of the batch le.

if not "%a:bc=%"=="%a%" echo yes

Testing for whether the rst command-line argument has


If variable a contains bc as a substring, echo been provided:
yes.
if not -%1-==-- echo Argument one provided if -%1 This test is a trick that uses string replacement, ==-- echo Argument one not provided & exit /b
discussed below.
This test does not work if the variable contains A robust looping over all command-line arguments using
SHIFT (for each command-line argument, ...):
a quotation mark.

Testing for starts with":

:argactionstart if -%1-==-- goto argactionend echo %1


& REM Or do any other thing with the argument shift

2.9

Wildcards

goto argactionstart :argactionend


A robust looping over all command-line arguments using
SHIFT without modifying %1, %2, etc.:
call :argactionstart %* echo Arg one: %1 & REM
%1, %2, etc. are unmodied in this location exit /b
:argactionstart if -%1-==-- goto argactionend echo %1
& REM Or do any other thing with the argument shift
goto argactionstart :argactionend exit /b
Transferring command-line arguments to environment
variables:
setlocal EnableDelayedExpansion REM Prevent aecting possible callers of the batch REM Without delayed
expansion, !arg%argno%! used below won't work. set
argcount=0 :argactionstart if -%1-==-- goto argactionend
set /a argcount+=1 set arg%argcount%=%1 shift goto
argactionstart :argactionend set argno=0 :loopstart set
/a argno+=1 if %argno% gtr %argcount% goto loopend
echo !arg%argno%! & REM Or do any other thing with
the argument goto loopstart :loopend

7
Thus, the following lines pass the same four arguments:
test.bat a b c d
test.bat a,b,c,d
test.bat a, b, c, d
test.bat a;b;c;d
test.bat a=b=c=d
test.bat a b,c;,;=d
Yes, even the line with a b,c;,;=d passes four arguments,
since a sequence of separating characters is considered a
single separator.
To have a space, comma or semicolon in the argument
value, you can pass the value enclosed in quotation marks.
However, the quotation marks become part of the argument value. To get rid of the enclosing quotation marks
when referring to the argument in the script, you can use
%~<number> described in #Percent tilde.
Links:

Looping over all command-line arguments, albeit not a


robust one:

Parameters / Arguments at ss64

for %%i in (%*) do ( echo %%i )

Escape Characters, Delimiters and Quotes at ss64

This looks elegant but is non-robust, maltreating arguments containing wildcards (*, ?). In particular, the
above for command replaces arguments that contain wildcards (*, ?) with le names that match them, or drops
them if no les match. Nonetheless, the above loop works
as expected as long as the passed arguments do not contain wildcards.

Using batch parameters at Microsoft

2.9 Wildcards
Many commands accept le name wildcards--characters
that do not stand for themselves and enable matching of
a group of lenames.

Finding the number of command-line arguments, in a Wildcards:


non-robust way:
* (asterisk): any sequence of characters
set argcount=0 for %%i in (%*) do set /a argcount+=1
Again, this does not work with arguments containing
wildcards.

? (question mark): a single character other than


a period (".) or, if part of a sequence of question
marks at the end of a maximum period-free part of
a le name, possibly zero number of characters; see
examples for clarication

The maximum possible number of arguments is greater


than 4000, as empirically determined on a Windows Vista
machine. The number can dier on Windows XP and
Examples:
Windows 7.
In passing arguments to a batch script, characters used for
argument separation are the following ones:
space
comma
semicolon
equal sign
tab character

dir *.txt
Matches Myle.txt, Plan.txt and any other le
with the .txt extension.
dir *txt
The period does not need to be included.
However, this will also match les named
without the period convention, such as myletxt.

2 USING THE WINDOWS COMMAND INTERPRETER


ren *.cxx *.cpp

2.10 User input

Renames all les with .cxx extension to have


You can get input from the user using the following meth.cpp extension.
ods:
dir a?b.txt
SET /P command
Matches les aab.txt, abb.txt, a0b.txt, etc.
Does not match ab.txt, since a question mark
followed by a character other than a question
mark or period cannot match zero characters.
Does not match a.b.txt, since a question mark
cannot match a period.
dir ???.txt

CHOICE command
Using type con >myle.txt, for which the multiline user input is terminated by user pressing Control
+ Z.

2.11 Percent tilde

Matches .txt, a.txt, aa.txt, and aaa.txt, among


others, since each question mark in the seWhen a command-line argument contains a le name,
quence followed by a period can match zero
special syntax can be used to get various information
number of characters.
about the le.
dir a???.b???.txt???
The following syntaxes expand to various information
Matches a.b.txt, among others. While the last about the le passed as %1:
question mark sequence is not followed by a The same syntax applies to single-letter variables created
period, it is still a sequence at the end of a max- by FOR command, such as "%%i.
imum period-free part of a le name.
To learn about this subject from the command line, type
dir ????????.txt & @REM eight question marks
call /?" or for /?".
Matches the same les as *.txt, since each le Links:
also has a short le name that has no more than
8 characters before .txt.
Parameters / Arguments at ss64
Quirk with short le names: the wildcard matching is performed both on long le names and the usually hidden
short 8 chars + period + 3 chars le names. This can lead
to bad surprises.

Using batch parameters at Microsoft


for at Microsoft

Unlike shells of some other operating systems, the


cmd.exe shell does not perform wildcard expansion (replacement of the pattern containing wildcards with the list
of le names matching the pattern) on its own. It is the
responsibility of each program to treat wildcards as such.
This enables such things as ren *.txt *.bat, since the ren
command actually sees the * wildcard rather than a list
of les matching the wildcard. Thus, echo *.txt does
not display les in the current folder matching the pattern
but rather literally displays "*.txt. Another consequence
is that you can write ndstr a.*txt without fearing that
the a.*txt part gets replaced with the names of some
les in the current folder. Furthermore, recursive ndstr
/s pattern *.txt is possible, while in some other operating systems, the "*.txt part would get replaced with the
le names found in the current folder, disregarding nested
folders.

2.12 Functions

Links:

The variable into which the result should be stored can be


specied on the calling line as follows:

Functions AKA subprograms can be emulated using


CALL, labels, SETLOCAL and ENDLOCAL.
An example of a function that determines arithmetic
power:
@echo o call :power 2 4 echo %result% rem Prints 16,
determined as 2 * 2 * 2 * 2 goto :eof rem __Function
power______________________ rem Arguments:
%1 and %2 :power setlocal set counter=%2 set interim_product=%1 :power_loop if %counter% gtr 1 (
set /A interim_product = %interim_product% * %1 set
/A counter = %counter% - 1 goto :power_loop ) endlocal
& set result=%interim_product% goto :eof

While the goto :eof at the end of the function is not


Commands accepting wildcards include ATTRIB, really needed, it has to be there in the general case in
which there is more than one function.
COPY, DIR, FINDSTR, FOR, REN, etc.

Wildcards at ss64
Using wildcard characters at Microsoft

@echo o call :sayhello result=world echo %result%


exit /b :sayhello set %1=Hello %2 REM Set %1 to set

2.13

Calculation

9
Uses the standard perecent notation for variable expansion.

the returning value exit /b


In the above example, exit /b is used instead of goto :eof
to the same eect.

set n1=40 & set n2=25


set /a n3=n1+n2
Avoids the percent notation around variable
names as unneeded for /a.

2.13 Calculation
Batch scripts can do simple 32-bit integer arithmetic and
bitwise manipulation using SET /a command. The largest
supported integer is 2147483647 = 2 ^ 31 - 1. The
smallest supported integer obtained by usual means is
2147483647, more of which later. The syntax is reminiscent of the C language.

set /a num="255^127
Encloses "^" in quotation marks to prevent its
special meaning for the command interpreter.
set /a n1 = (10 + 5)/5
The spaces around = do not matter with /a.
However, getting used to it lends itself to writing set var = value without /a, which sets the
value of var " rather than var.

Arithmetic operators include *, /, % (modulo), +, . In


a batch, modulo has to be entered as "%%".
Bitwise operators interpret the number as a sequence of
32 binary digits. These are ~ (complement), & (and), |
(or), ^ (xor), << (left shift), >> (right shift).

set /a n1=2+3,n2=4*7

A logical operator of negation is !: it turns zero into one


and non-zero into zero.

set /a n1=n2=2

A combination operator is ,: it allows more calculations


in one set command.
Combined assignment operators are modeled on "+=",
which, in a+=b, means a=a+b. Thus, a-=b means
a=a-b. Similarly for *=, /=, %=, &=, ^=, |=, <<=, and
>>=.
The precedence order of supported operators, each predecence level separated by , is as follows: ( ) * / % +
- << >> & ^ | = *= /= %= += -= &= ^= |=
<<= >>= ,
As some of the operators have special meaning for the
command interpreter, an expression using them needs to
be enclosed in quotation marks, such as this:

Performs two calculations.


Has the same eect as n1=2,n2=2.
set n1=40 & set n2=25 & set /a n3=n1+n2
Works as expected.
set /a n1=2,n2=3,n3=n1+n2
Works as expected.
set n1=40 & set n2=25 & set /a n3=%n1%+%n2%
Does not work unless n1 and n2 were set previously. The variable specications "%n1%"
and "%n2"% get expanded before the rst set
command is executed. Dropping percent notation makes it work.
set /a n1=2,n2=3,n3=%n1%+%n2%
Does not work unless n1 and n2 were set previously, for the reason stated in the previous
example.

set /a num="255^127
set /a num=255^127
Alternative placement of quotation marks.

An example calculation that prints prime numbers:

@echo o setlocal set n=1 :print_primes_loop set


/a n=n+1 set cand_divisor=1 :print_primes_loop2
Escape ^ using ^ instead of quotation marks. set
/a
cand_divisor=cand_divisor+1
set
/a
cand_divisor_squared=cand_divisor*cand_divisor
The smallest supported integer is 2147483647, but you if %cand_divisor_squared% gtr %n% echo Prime
%n% & goto :print_primes_loop set /a modcan get 2147483648 like this:
ulo=n%%cand_divisor if %modulo% equ 0 goto
:print_primes_loop & REM Not a prime goto
set /a num=~2147483647
:print_primes_loop2
set /a num=255^^127

Examples:
set n1=40 & set n2=25
set /a n3=%n1%+%n2%

Links:
set at ss64.com
set at Microsoft

10

2.14 Limitations

BUILT-IN COMMANDS

3.3 BREAK

There is no touch command familiar from other operat- In Windows versions based on Windows NT, does nothing systems. The touch command would modify the last- ing; kept for compatibility with MS DOS.
modication timestamp of a le without changing its con- Links:
tent.
One workaround, with unclear reliability and applicability
across various Windows versions, is this:
copy /b le.txt+,,

break at Microsoft

3.4 CALL
Calls one batch program from another, or calls a subprogram within a single batch program. For calling a subprogram, see Functions section.

Links:

Windows recursive touch command at supeLinks:


ruser.com
Windows version of the Unix touch command at
stackoverow.com

Built-in commands

These commands are all built in to the command interpreter itself, and cannot be changed. Sometimes this is
because they require access to internal command interpreter data structures, or modify properties of the command interpreter process itself.

call at ss64.com
call at Microsoft

3.5 CD
Changes to a dierent directory, or displays the current
directory. However, if a dierent drive letter is used, it
does not switch to that dierent drive or volume.
Examples:
cd

3.1

Overview

cd C:\Program Files

3.2

ASSOC

cd \Program Files

Associates an extension with a le type (FTYPE), displays existing associations, or deletes an association. See
also FTYPE.
Examples:
assoc
Lists all associations, in the format "<le
extension>=<le type>", as, for example,
".pl=Perl or ".xls=Excel.Sheet.8.
assoc | nd ".doc
Lists all associations containing ".doc substring.
Links:
assoc at ss64.com
assoc at Microsoft
Making Python scripts run on Windows without
specifying .py extension at stackoverow

cd Documents
cd %USERPROFILE%
cd /d C:\Program Files
Changes to the directory of the C: drive even
if C: is not the current drive.
C: & cd C:\Program Files.
Changes to the directory of the C: drive even
if C: is not the current drive.
cd ..
Changes to the parent directory. Does nothing
if already in the root directory.
cd ..\..
Changes to the parent directory two levels up.
C: & cd C:\Windows\System32 & cd ..\..\Program
Files
Uses ".. to navigate through the directory
three up and down

3.10

DEL

No surrounding quotes are needed around paths with


spaces.
Links:

11
Does the same as the above command.
copy File.txt
Issues an error message, as File.txt cannot be
copied over itself.

cd at ss64.com
chdir at Microsoft

3.6

copy File.txt My Directory


Copies File.txt into My Directory directory,
assuming My Directory exists.

CLS

Clears the screen.

3.8

Copies File1.txt to File2.txt, overwriting


File2.txt if conrmed by the user or if run from
a batch script.

CHDIR

A synonym of CD.

3.7

copy File1.txt File2.txt

copy Dir1 Dir2


Copies all les directly located in directory
Dir1 into Dir2, assuming Dir1 and Dir2 are directories. Does not copy les located in nested
directories of Dir1.

COLOR

Sets the console foreground and background colors.


Examples:

copy *.txt *.bak


For each *.txt le in the current folder, makes
a copy ending with bak rather than txt.

color f9
Use white background and blue foreground.
color
Restore the original color setting.

Links:
copy at ss64.com
copy at Microsoft

Links:
color at ss64.com

3.10 DEL

color at Microsoft

Deletes les. Use with caution, especially in combination with wildcards. Only deletes les, not directories,
for which see RD. For more, type del /?".

3.9

COPY

Copies les. See also MOVE.


Examples:

Examples:
del File.txt
del /s *.txt

copy F:\File.txt
Copies the le into the current directory, assuming the current directory is not F:\.
copy F:\My File.txt
As above; quotation marks are needed to surround a le with spaces.
copy F:\*.txt

Deletes the les recursively including nested


directories, but keeps the directories; mercilessly deletes all matching les without asking
for conrmation.
del /p /s *.txt
As above, but asks for conrmation before every single le.

Copies the les located at F:\ and ending in Links:


dot txt into the current directory, assuming the
current directory is not F:\.
del at ss64.com
copy F:\*.txt .

del at Microsoft

12

3.11 DIR

dir /o-s
Orders the les by the size descending; the impact on folder order is unclear.

Lists the contents of a directory. Oers a range of options. Type dir /?" for more help.
Examples:

dir /-c /o-s /a-d


Lists les ordered by size descending, omitting the thousands separator via /-C, excluding
folders.

dir
Lists the les and folders in the current folder,
excluding hidden les and system les; uses a
dierent manner of listing if DIRCMD variable is non-empty and contains switches for
dir.

BUILT-IN COMMANDS

dir /s /b /od
Lists the contents of the directory and all subdirectories recursively, ordering the les in
each directory by the date of last modication.
The ordering only happens per directory; the
complete set of les so found is not ordered as
a whole.

dir D:
dir /b C:\Users
dir /s
Lists the contents of the directory and all sub- Links:
directories recursively.
dir /s /b

dir at ss64.com

Lists the contents of the directory and all sub dir at Microsoft
directories recursively, one le per line, displaying complete path for each listed le or di3.12 DATE
rectory.
dir *.txt
Lists all les with .txt extension.

Displays or sets the date. The way the date is displayed


depends on country settings. Date can also be displayed
using echo %DATE%".

dir /a

Getting date in the iso format, like 2000-01-28": That


Includes hidden les and system les in the list- is nowhere easy, as the date format depends on country
settings.
ing.

dir /ah
Lists hidden les only.

If you can assume the format of Mon 01/28/2000,


the following will do:
set
isodate=%date:~10,4%-%date:~4,2%%date:~7,2%

dir /ad
Lists directories only. Other letters after /A
include S, I, R, A and L.
dir /ahd
Lists hidden directories only.
dir /a-d
Lists les only, omitting directories.
dir /a-d-h
Lists non-hidden les only, omitting directories.
dir /od

Links:
date at ss64.com
date at Microsoft
How to get current datetime on Windows command
line, in a suitable format for using in a lename? at
stackoverow

3.13 ECHO

Displays messages, or turns command echoing on or o.


Orders the les and folders by the date of last
modication. Other letters after /O include N Examples:
(by name), E (by extension), S (by size), and
echo on
G (folders rst)

3.16

ERASE

13

@echo o

3.16 ERASE

echo Hello

A synonym of DEL.

echo hello
Displays the quotes too.
echo %PATH%

3.17 EXIT

echo ECHO Owner ^& son

Exits the DOS console or, with /b, only the currently running batch or the currently executed subroutine. If used
without /b in a batch le, causes the DOS console calling
the batch to close.

echo 1&echo 2&echo 3

Examples:

Displays the contents of PATH variable.

Displays three strings, each followed by a newline.

exit
exit /b

Displaying a string without a newline requires a trick:


set <NUL /p=Output of a command:
Displays Output of a command:". The output
of the next command will be displayed immediately after ":".
set <NUL /p=Current time: & time /t

Links:
exit at ss64.com
exit at Microsoft

3.18 FOR

Displays Current time: " followed by the outIterates over a series of values, executing a command.
put of time /t.
(set <NUL /p=Current time: & time /t) >tmp.txt

In the following examples, %i is to be used from the command line while %%i is to be used from a batch.

Like before, with redirecting the output of


Examples:
both commands to a le.
Links:
echo at ss64.com
echo at Microsoft

3.14 ELSE
An example:
if exist le.txt ( echo The le exists. ) else ( echo The
le does not exist. )
See also IF.

3.15 ENDLOCAL
Ends local set of environment variables started using
SETLOCAL. Can be used to create subprograms: see
Functions.
Links:
endlocal at ss64.com
endlocal at Microsoft

for %%i in (1,2,3) do echo %%i


In a batch, echoes 1, 2, and 3. In a batch, the
command must use a double percent sign.
The remaining examples are intended to be directly pasted into a command line, so they use
a single percent sign and include "@" to prevent repetitive display.
for %i in (1,2,3) do @echo %i
From a command line, echoes 1, 2, and 3.
The for command tries to interpret the items
as le names and as patterns of le names containing wildcards.
It does not complain if the items do not match
existing le names, though.
for %i in (1,2,a*d*c*e*t) do @echo %i
Unless you happen to have a le matching the
third pattern, echoes 1 and 2, discarding the
third item.
for %i in (1 2,3;4) do @echo %i
Echoes 1, 2, 3, and 4. Yes, a mixture of item
separators is used.

14

for %i in (*.txt) do @echo %i


Echoes le names of les located in the current
folder and having the .txt extension.
for %i in (C:\Windows\system32\*.exe) do
@echo %i
Echoes le names matching the pattern.
for /r %i in (*.txt) do @echo %i
Echoes le names with full paths, of les having the extension .txt located anywhere in the
current folder including nested folders.
for /d %i in (*) do @echo %i
Echoes the names of all folders in the current
folder.
for /r /d %i in (*) do @echo %i
Echoes the names including full paths of all
folders in the current folder, including nested
folders.
for /l %i in (1,1,10) do @echo %i
Echoes the numbers from 1 to 10.
for /f tokens=*" %i in (list.txt) do @echo %i
For each line in a le, echoes the line.
for /f tokens=*" %i in (list1.txt list2.txt) do @echo
%i
For each line in the les, echoes the line.
for /f tokens=*" %i in (*.txt) do @echo %i
Does nothing. Does not accept wildcards to
match le names.
for /f tokens=1-3 delims=:" %a in ("First:Second::
Third") do @echo %c-%b-%a
Parses a string into tokens delimited by ":".
The quotation marks indicate the string is not
a le name.
The second and third tokens are stored in %b
and %c even though %b and %c are not expressly mentioned in the part of the command
before do.
The two consecutive colons are treated as one
separator; %c is not "" but rather Third.

BUILT-IN COMMANDS

As above, just that the 4th and 5th items get


captured in %d as "Fourth:Fifth", including
the separator.
for /f tokens=1-3* delims=:, %a in
(First,Second,:Third:Fourth:Fifth") do @echo
%c-%b-%a: %d
Multiple delimiters are possible.
for /f tokens=1-3 %a in (First Second
Third,item) do @echo %c-%b-%a
The default delimiters are space and tab. Thus,
they dier from the separators used to separate
arguments passed to a batch.
for /f tokens=*" %i in ('cd') do @echo %i
For each line of the result of a command,
echoes the line.
for /f tokens=*" %i in ('dir /b /a-d-h') do @echo
%~nxai
For each non-hidden le in the current folder,
displays the le attributes followed by the le
name. In the string "%~nxai, uses the syntax
described at #Percent tilde.
for /f usebackq tokens=*" %i in (`dir /b /a-d-h`) do
@echo %~nxai
As above, but using the backquote character
(`) around the command to be executed.
for /f tokens=*" %i in ('tasklist ^| sort ^& echo
End') do @echo %i
Pipes and ampersands in the command to be
executed must be escaped using caret (^).
(for %i in (1,2,3) do @echo %i) > anyoldtemp.txt
To redirect the entire result of a for loop, place
the entire loop inside brackets before redirecting. Otherwise, the redirection will tie to the
body of the loop, so each new iteration of the
body of the loop will override the results of the
previous iterations.
for %i in (1,2,3) do @echo %i > anyoldtemp.txt
An example related to the one above. It shows
the consequence of failing to put the loop inside brackets.

There is no continue statement like that in C and it cannot


Does some of the job of the cut command be simulated by goto as a goto (even if it doesn't jump out
from other operating systems.
of the loop body) destroys loop bookkeeping. Try
for /f tokens=1-3* delims=:" %a in ("First:
Second::Third:Fourth:Fifth") do @echo %c-%b%a: %d

for %%i in (a b c) do ( echo 1 %%i goto :cont echo 2


%%i :cont echo 3 %%i )

3.21

IF

However, putting the body in a subroutine works:

15

3.21 IF

for %%i in (a b c) do call :for_body %%i exit /b


Conditionally executes a command. Documentation is
:for_body echo 1 %1 goto :cont echo 2 %1 :cont exit /b
available by entering IF /? to CMD prompt.
Available elementary tests:

Links:
for at ss64.com
for at Microsoft

3.19 FTYPE
Displays or sets the command to be executed for a le
type. See also ASSOC.
Examples:
ftype
Lists all associations of commands to be
executed with le types, as, for example,
'Perl="C:\Perl\bin\perl.exe "%1 %*'
ftype | nd Excel.Sheet
Lists only associations whose display line contains Excel.Sheet
Links:

exist <lename>
<string>==<string>
<expression1> equ <expression2> -- equals
<expression1> neq <expression2> -- not equal
<expression1> lss <expression2> -- less than
<expression1> leq <expression2> -- less than or
equal
<expression1> gtr <expression2> -- greater then
<expression1> geq <expression2> -- greater than or
equal
dened <variable>
errorlevel <number>
cmdextversion <number>
To each elementary test, not can be applied. Apparently
there are no operators like AND, OR, etc. to combine
elementary tests.

ftype at ss64.com

The /I switch makes the == and equ comparisons ignore


case.

ftype at Microsoft

An example:

if not exist %targetpath% ( echo Target path not found.


Making Python scripts run on Windows without
exit /b )
specifying .py extension at stackoverow
Examples:

3.20 GOTO
Goes to a label.
An example:
goto :mylabel echo Hello 1 REM Hello 1 never gets
printed. :mylabel echo Hello 2 goto :eof echo Hello 3
REM Hello 3 never gets printed. Eof is a virtual label
standing for the end of le.

if not 1 equ 0 echo Not equal


if 1 equ 0 echo A & echo B
Does nothing; both echo commands are subject to the condition.
if not 1 equ 0 goto :mylabel
if not a geq b echo Not greater

Goto within the body of a for loop makes cmd forget


about the loop, even if the label is within the same loop
body.
Links:

if b geq a echo Greater


if b geq A echo Greater in a case-insensitive comparison

goto at ss64.com

if B geq a echo Greater in a case-insensitive comparison

goto at Microsoft

if 0 equ 00 echo Numerical equality

16

BUILT-IN COMMANDS

if not 0==00 echo String inequality

3.24 MOVE

if 01 geq 1 echo Numerical comparison

Moves les or directories between directories, or renames


them. See also REN.

if not 01 geq 1 echo String comparison


if 1 equ 0 (echo Equal) else echo Unequal
Notice the brackets around the positive thenpart to make it work.

Examples:
move File1.txt File2.txt
Renames File1.txt to File2.txt, overwriting
File2.txt if conrmed by the user or if run from
a batch script.

if not a==A echo Case-sensitive inequality


if /i a==A echo Case-insensitive equality

move File.txt Dir


Moves File.txt le into Dir directory, assuming File.txt is a le and Dir is a directory;
overwrites target le Dir\a.txt if conditions for
overwriting are met.

if /i==/i echo This does not work


if "/i"=="/i echo Equal, using quotation marks to
prevent the literal meaning of /i

move Dir1 Dir2


Renames directory Dir1 to Dir2, assuming
Dir1 is a directory and Dir2 does not exist.

Links:
if at ss64.com

move Dir1 Dir2

if at Microsoft

3.22 MD
Creates a new directory or directories. Has a synonym
MKDIR; see also its antonym RD.
Examples:

Moves directory Dir1 into Dir2, resulting in


existence of Dir2\Dir1, assuming both Dir1
and Dir2 are existing directories.
move F:\File.txt
Moves the le to the current directory.
move F:\*.txt
Moves the les located at F:\ and ending in
dot txt into the current directory, assuming the
current directory is not F:\.

md Dir
Creates one directory in the current directory.

Links:

md Dir1 Dir2
Creates two directories in the current directory.
md My Dir With Spaces

move at ss64.com
move at Microsoft

3.25 PATH

Creates a directory with a name containing


Displays or sets the value of the PATH environment varispaces in the current directory.
able.
Links:
md at ss64.com
md at Microsoft

3.23 MKDIR
A synonym for MD.

Links:
path at ss64.com
path at Microsoft

3.26 PAUSE
Prompts the user and waits for a line of input to be entered.

3.31

REN

17

3.27 POPD

Removes the directory Dir1 including all the


les and subdirectories in it, asking for conrmation once before proceeding with the removal. To delete les recursively in nested directories with a conrmation per le, use DEL
with /s switch.

Changes to the drive and directory poped from the directory stack. The directory stack is lled using the PUSHD
command.
Links:

rd /q /s Dir1
popd at ss64.com

Like above, but without asking for conrmation.

popd at Microsoft
Links:

3.28 PROMPT
rd at ss64.com
Can be used to change or reset the cmd.exe prompt. It
sets the value of the PROMPT environment variable.
C:\>PROMPT MyPrompt$G
MyPrompt>PROMPT C:\>

MyPrompt>CD

C:\

rmdir at Microsoft

3.31 REN

Renames les and directories.


The PROMPT command is used to set the prompt to
MyPrompt>". The CD shows that the current directory Examples:
path is C:\". Using PROMPT without any parameters
ren lewithtpyo.txt lewithtypo.txt
sets the prompt back to the directory path.
Links:
prompt at ss64.com
prompt at Microsoft

3.29 PUSHD

ren *.cxx *.cpp


Links:
ren at ss64.com
rename at Microsoft
How does the Windows RENAME command interpret wildcards?, superuser.com

Pushes the current directory onto the directory stack,


making it available for the POPD command to retrieve,
and, if executed with an argument, changes to the direc- 3.32
tory stated as the argument.
Links:
pushd at ss64.com
pushd at Microsoft

3.30 RD

RENAME

This is a synonym of REN command.

3.33 REM
Used for remarks in batch les, preventing the content of
the remark from being executed.
An example:

Removes directories. See also its synonym RMDIR and REM A remark that does not get executed echo Hello
antonym MD. Per default, only empty directories can be REM This remark gets displayed by echo echo Hello
& REM This remark gets ignored as wished :: This
removed. Also type rd /?".
sentence has been marked as a remark using double
Examples:
colon.
rd Dir1
rd Dir1 Dir2

REM is typically placed at the beginning of a line. If


placed behind a command, it does not work, unless preceded by an ampersand, as shown in the example above.

rd My Dir With Spaces

An alternative to REM is double colon.

rd /s Dir1

Links:

18

rem at ss64.com
rem at Microsoft

3.34 RMDIR

BUILT-IN COMMANDS

after the execution reaches the location of their use rather


than at an earlier point.
The following is an example of using delayed expansion
in a script that prints the specied number of rst lines
of a le, providing some of the function of the command
head known from other operating systems:

This is a synonym of RD.

@echo o call :myhead 2 File.txt exit /b :: Function


myhead :: =============== :: %1 - lines count, %2
- le name :myhead setlocal EnableDelayedExpansion
3.35 SET
set counter=1 for /f tokens=*" %%i in (%2) do ( echo
Displays or sets environment variables. With /P switch, %%i set /a counter=!counter!+1 if !counter! gtr %1 exit
it asks the user for input, storing the result in the vari- /b ) exit /b
able. With /A switch, it performs simple arithmetic calculations, storing the result in the variable. With string Links:
assignments, there must be no spaces before and after
the equality sign; thus, set name = Peter does not work,
setlocal at ss64.com
while set name=Peter does.
EnableDelayedExpansion at ss64.com
Examples:
setlocal at Microsoft

set
Displays a list of environment variables

3.37 SHIFT

set HOME

Shifts the batch le arguments along, but does not aect


Displays the values of the environment vari- %*. Thus, if %1=Hello 1, %2=Hello 2, and %3=Hello
3, then, after SHIFT, %1=Hello 2, and %2=Hello 3, but
ables whose names start with HOME
%* is Hello 1 Hello 2 Hello 3.
set MYNUMBER=56
Links:
set HOME=%HOME%;C:\Program Files\My Bin
Folder
shift at ss64.com
set /P user_input=Enter an integer:

shift at Microsoft

set /A result = 4 * ( 6 / 3 )
Sets the result variable with the result of a cal- 3.38 START
culation. See also #Calculation.
Starts a program in new window, or opens a document.
Uses an unclear algorithm to determine whether the rst
Links:
passed argument is a window title or a program to be executed; hypothesis: it uses the presence of quotes around
set at ss64.com
the rst argument as a hint that it is a window title.
set at Microsoft

3.36 SETLOCAL
When used in a batch le, makes all further changes to environment variables local to the current batch le. When
used outside of a batch le, does nothing. Can be ended
using ENDLOCAL. Exiting a batch le automatically
calls end local. Can be used to create subprograms: see
Functions.
Furthermore, can be used to enable delayed expansion
like this: setlocal EnableDelayedExpansion. Delayed
expansion consists in the names of variables enclosed in
exclamation marks being replaced with their values only

Examples:
start notepad.exe & echo Done.
Starts notepad.exe, proceeding to the next
command without waiting for nishing the
started one. Keywords: asynchronous.
start notepad.exe
Launches a new console window with
notepad.exe being its title, apparently an
undesired outcome.
start "" C:\Program
plorer\iexplore.exe

Files\Internet

Ex-

3.40

TITLE

19

Starts Internet Explorer. The empty "" passed 3.40 TITLE


as the rst argument is the window title of a
console that actually does not get opened, or at Sets the title displayed in the console window.
least not visibly so.
Links:
start
C:\Program
Files\Internet
Explorer\iexplore.exe
title at ss64.com
Launches
a
new
console
window
with
C:\Program
Files\Internet
Explorer\iexplore.exe being its title, apparently
an undesired outcome.
start /wait notepad.exe & echo Done.

title at Microsoft

3.41 TYPE

Starts notepad.exe, waiting for it to end before Prints the content of a le or les to the output.
proceeding.
Examples:
start /low notepad.exe & echo Done.
As above, but starting the program with a low
priority.
start "" MyFile.xls
Opens the document in the program assigned
to open it.

type lename.txt
type a.txt b.txt
type *.txt
type NUL > tmp.txt

start
Starts a new console (command-line window)
in the same current folder.
start .
Opens the current folder in Windows Explorer.
start ..

Create an empty le (blank le).


Links:
type at ss64.com
type at Microsoft

Opens the parent folder in Windows Explorer.


start "" mailto:"

3.42 VER

Starts the application for writing a new email.

Shows the command processor or operating system ver start /b TODO:example-application-where-this-is-useful


sion.
Starts the application without opening a new C:\>VER Microsoft Windows XP [Version 5.1.2600]
console window, redirecting the output to the C:\>
console from which the start command was
called.
Some version strings:
Links:
start at ss64.com
start at Microsoft

Microsoft Windows XP [Version 5.1.2600]


Microsoft Windows [Version 6.0.6000]
...

3.39 TIME
The word version appears localized.
Displays or sets the system time.

Links:

Links:
time at ss64.com

ver at ss64.com

time at Microsoft

ver at Microsoft

20

3.43 VERIFY
Sets or clears the setting to verify whether COPY les etc.
are written correctly.

EXTERNAL COMMANDS

To remove an attribute, attach a '-' in front of its letter


Attributes:
A - Archived

Links:

H - Hidden

verify at ss64.com

S - System

verify at Microsoft

R - Read-only
...and possibly others.

3.44 VOL
Examples:
Displays volume labels.
attrib

Links:

Displays the attributes of all les in the current


directory.

vol at ss64.com
vol at Microsoft

attrib File.txt
Displays the attributes of the le.

External commands

External commands available to Windows command interpreter are separate executable program les, supplied
with the operating system by Microsoft, or bundled as
standard with the third-party command interpreters. By
replacing the program les, the meanings and functions
of these commands can be changed.
Many, but not all, external commands support the "/?"
convention, causing them to write on-line usage information to their standard output and then to exit with a status
code of 0.

4.1

Adds the Read-only attribute to the le.


attrib -a File.txt
Removes the Archived attribute from the
le.
attrib -a +r File.txt
Removes the Archived attribute and adds the
Read-only attribute to the le.
attrib +r *.txt
Acts on a set of les.

AT

Schedules a program to be run at a certain time. See also


SCHTASKS.
Links:

attrib /S +r *.txt
Acts recursively in subdirectories.
For more, type attrib /?".

at at ss64.com
at at Microsoft

4.2

attrib +r File.txt

ATTRIB

Displays or sets le attributes. With no arguments, it displays the attributes of all les in the current directory.
With no attribute modication instructions, it displays the
attributes of the les and directories that match the given
search wildcard specications. Similar to chmod of other
operating systems.
Modication instructions:
To add an attribute, attach a '+' in front of its letter.

Links:
attrib at ss64.com
attrib at Microsoft

4.3 BCDEDIT
(Not in XP). Edits Boot Conguration Data (BCD) les.
For more, type bcdedit /?".
Links:
bcdedit at ss64.com
bcdedit at Microsoft

4.9

CMD

4.4

21

CACLS

Presents the user with a yes/no question, setting the error level to 1 for yes and to 2 for no.
If the user presses Control + C, the error level
is 0.

Shows or changes discretionary access control lists (DACLs). See also ICACLS. For more, type cacls /?".
Links:

choice /c rgb /m Which color do you prefer


Presents the user with a question, and indicates
the letters for the user. Responds to user pressing r, g or b, setting the error level to 1, 2 or
3.

cacls at ss64.com
cacls at Microsoft

4.5

CHCP

An alternative is set /p"; see SET.

Displays or sets the active code page number. For more, Links:
type chcp /?".
choice at ss64.com
Links:
chcp at ss64.com
chcp at Microsoft

4.6

CHKDSK

choice at Microsoft

4.9 CMD
Invokes another instance of Microsofts CMD.
Links:

Checks disks for disk problems, listing them and repairing them if wished. For more, type chkdsk /?".
Links:

cmd at ss64.com
cmd at Microsoft

chkdsk at ss64.com
chkdsk at Microsoft

4.10 COMP
Compares les. See also FC.

4.7

CHKNTFS

Links:

Shows or sets whether system checking should be run


comp at ss64.com
when the computer is started. The system checking is
done using Autochk.exe. The NTFS part of the com comp at Microsoft
mand name is misleading, since the command works not
only with NTFS le system but also with FAT and FAT32
4.11 COMPACT
le systems. For more, type chkntfs /?".
Links:
chkntfs at ss64.com

Shows or changes the compression of les or folders on


NTFS partitions.
Links:

chkntfs at Microsoft
compact at Microsoft

4.8

CHOICE
4.12 CONVERT

Lets the user choose one of multiple options by pressing


a single key, and sets the error level as per the chosen Converts a volume from FAT16 or FAT32 le system to
option. Absent in Windows 2000 and Windows XP, it NTFS le system.
was reintroduced in Windows Vista, and has remained in
Links:
Windows 7 and 8.
Examples:
choice /m Do you agree

convert at ss64.com
convert at Microsoft

22

EXTERNAL COMMANDS

4.13 DEBUG

4.17 DOSKEY

Allows to interactively examine le and memory contents


in assembly language, hexadecimal or ASCII. Available
in 32-bit Windows including Windows 7; the availability
in 64-bit Windows is unclear. In modern Windows, useful
as a quick hack to view hex content of a le. Keywords:
hex dump, hexdump, hexadecimal dump, view hex, view
hexadecimal, disassembler.

Above all, creates macros known from other operating


systems as aliases. Moreover, provides functions related
to command history, and enhanced command-line editing. Macros are an alternative to very short batch scripts.

Debug oers its own command line. Once on its command like, type "?" to nd about debug commands.
To view hex of a le, invoke debug.exe with the le name
as a parameter, and then repeatedly type d followed by
enter on the debug command line.
Limitations:
Being a DOS program, debug chokes on long le
names. Use dir /x to nd the 8.3 le name, and apply
debug on that one.

Macro-related examples:
doskey da=dir /s /b
Creates a single macro called da
doskey np=notepad $1
Creates a single macro that passes its rst argument to notepad.
doskey /macrole=doskeymacros.txt
Loads macro denitions from a le.
doskey /macros

Debug cannot view larger les.


Links:

Lists all dened macros with their denitions.


doskey /macros | nd da

Debug at technet.microsoft.com

Lists all macro denitions that contain da as


a substring; see also FIND.

Debug for MS-DOS at technet.microsoft.com


W:Debug (command)

4.14 DISKCOMP

Command history-related examples:


doskey /history
Lists the complete command history.

Compares the content of two oppies.


Links:

doskey /history | nd dir


Lists each line of command history that contains dir as a substring

diskcomp at ss64.com
diskcomp at Microsoft

doskey /listsize=100
Sets the size of command history to 100.

4.15 DISKCOPY
Copies the content of one oppy to another.
Links:
diskcopy at ss64.com
diskcopy at Microsoft

To get help on doskey from command line, type doskey


/?".
Links:
doskey at ss64.com
doskey at Microsoft

4.16 DISKPART
4.18 DRIVERQUERY
Shows and congures the properties of disk partitions.
Links:
diskpart at ss64.com

Shows all installed device drivers and their properties.


Links:

diskpart at Microsoft, for XP

driverquery at ss64.com

diskpart at Microsoft

driverquery at Microsoft

4.21

FINDSTR

4.19 FC
Compares les, displaying the dierences in their content
in a peculiar way.
Examples:
fc File1.txt File2.txt >NUL && Echo Same || echo
Dierent or error
Detects dierence using the error level of fc.
The error level of zero means the les are the
same; non-zero can mean the les dier but
also that one of the les does not exist.
Links:
fc at ss64.com
fc at Microsoft

23
type *.txt 2>NUL | nd /C /V ""
Outputs the sum of line counts of the les
ending in ".txt in the current folder. The
2>NUL is a redirection of standard error
that removes the names of les followed by
empty lines from the output.
nd Schnheit *.txt
If run from a batch le saved in unicode
UTF-8 encoding, searches for the search term
Schnheit in UTF-8 encoded *.txt les. For
this to work, the batch le must not contain
the byte order mark written by Notepad when
saving in UTF-8. Notepad++ is an example
of a program that lets you write UTF-8 encoded plain text les without byte order mark.
While this works with nd command, it does
not work with #FINDSTR.
nd Copyright C:\Windows\system32\a*.exe

4.20 FIND

Works with binary les no less than text les.


Searches for a string in les or input, outputting matching lines. Unlike FINDSTR, it cannot search folders re- Links:
cursively, cannot search for a regular expression, requires
quotation marks around the sought string, and treats space
nd at ss64.com
literally rather than as a logical or.
Examples:
nd "(object *.txt

nd at Microsoft

4.21 FINDSTR

dir /S /B | nd receipt
Searches for regular expressions or text strings in les.
Does some of the job of grep command known from
Prints all non-matching lines in the output of other operating systems, but is much more limited in the
regular expressions it supports.
the dir command, ignoring letter case.
Treats space in a regular expression as a disjunction AKA
nd /C inlined *.h
logical or unless prevented with /c option.
dir /S /B | nd /I /V receipt

Instead of outputting the matching lines, out- Examples:


puts their count. If more than one le is
searched, outputs one count number per le
ndstr /s "[0-9][0-9].*[0-9][0-9]" *.h *.cpp
preceded with a series of dashes followed by
the le name; does not output the total num Searches recursively all les whose name ends
ber of matching lines in all les.
with dot h or dot cpp, priting only lines that
contain two consecutive decimal digits fol nd /C /V "" < le.txt
lowed by anything followed by two consecutive decimal digits.
Outputs the number of lines AKA line count
in le.txt. Does the job of wc -l of other
ndstr a.*b a.*c File.txt
operating systems. Works by treating "" as a
string not found on the lines. The use of redi Outputs all lines in File.txt that match any of
rection prevents the le name from being outthe two regular expressions separated by the
put before the number of lines.
space. Thus, the eect is one of logical or on
regular
expressions.
type le.txt | nd /C /V ""
Like the above, with a dierent syntax.

ndstr /r /c:"ID: *[0-9]*" File.txt

24

EXTERNAL COMMANDS

Outputs all lines in File.txt that match the sin Works with binary les no less than text les.
gle regular expression containing a space. The
use of /c prevents the space from being treated Limitations of the regular expressions of ndstr, as
as a logical or. The use of /r switches the reg- compared to grep":
ular expression treatment on, which was disabled by default by the use of /c. To test this,
No support of groups -- "\(", "\)".
try the following:
No support of greedy iterators -- "*?".
echo ID: 12|ndstr /r /c:"ID: *[0-9]*$"
Matches.
No support of zero or one of the previous -- "?".
echo ID: 12|ndstr /c:"ID: *[0-9]*$"
And more.
Does not match, as the search string
is not interpreted as a regular expression.
Other limitations: There is a variety of limitations and
strange behaviors as documented at What are the undoc echo ID: abc|ndstr ID: *[0-9]*$"
Matches despite the output of echo umented features and limitations of the Windows FINDfailing to match the complete regular STR command?.
expression: the search is interpreted Also consider typing ndstr /?".
as one for lines matching ID:" or
Links:
"*[0-9]*$".
ndstr /ric:"id: *[0-9]*" File.txt

ndstr at ss64.com

Does the same as the previous example, but in


a case-insensitive manner.

ndstr at Microsoft

While ndstr enables this sort of accumulation


of switches behind a single "/", this is not possible with any command. For instance, dir
/bs does not work, while dir /b /s does.

What are the undocumented features and limitations


of the Windows FINDSTR command? at StackOverow

To test this, try the following:


echo ID: 12|ndstr /ric:"id: *[0-9]*$"
echo ID: ab|ndstr /ric:"id: *[0-9]*$"
ndstr /msric:"id: *[0-9]*" *.txt

4.22 FORMAT
Formats a disk to use Windows-supported le system
such as FAT, FAT32 or NTFS, thereby overwriting the
previous content of the disk. To be used with great caution.

Like above, but recursively for all les per


/s, displaying only matching les rather than Links:
matching lines per /m.
format at ss64.com
echo hel lo | ndstr /c:"hel lo /c:world
format at Microsoft
/c switch can be used multiple times to create
logical or.
echo \hello\ | ndstr "\hello\"

4.23 FSUTIL

Does not match. Backslash before quotation A powerful tool performing actions related to FAT and
marks and multiple other characters acts as an NTFS le systems, to be ideally only used by powerusers
escape; thus, \" matches ".
with an extensive knowledge of the operating systems.
echo \hello\ | ndstr "\\hello\\"
Matches. Double backslash passed to ndstr
stands for a single backslash.
echo \hello\ | ndstr \hello\
Matches. None of the single backslashes
passed to ndstr is followed by a character on
which the backslash acts as an escape.
ndstr /m Microsoft C:\Windows\system32\*.com

Links:
fsutil at ss64.com
fsutil at Microsoft
Fsutil: behavior
Fsutil: dirty
Fsutil: le
Fsutil: fsinfo

4.27

ICACLS
Fsutil: hardlink
Fsutil: objectid
Fsutil: quota
Fsutil: reparsepoint
Fsutil: sparse

25

4.27 ICACLS
(Not in XP) Shows or changes discretionary access control lists (DACLs) of les or folders. See also CACLS.
Fore more, type icacls /?".
Links:

Fsutil: usn

icacls at ss64.com

Fsutil: volume

icacls at Microsoft

4.24 GPRESULT

4.28 IPCONFIG

Displays group policy settings and more for a user or a Displays Windows IP Conguration. Shows conguracomputer.
tion by connection and the name of that connection (i.e.
Ethernet adapter Local Area Connection) Below that the
Links:
specic info pertaining to that connection is displayed
such as DNS sux and ip address and subnet mask.
gpresult at ss64.com
Links:
gpresult at Microsoft
Wikipedia:Group Policy

4.25 GRAFTABL

ipcong at ss64.com
ipcong at Microsoft

4.29 LABEL

Enables the display of an extended character set in graph- Adds, sets or removes a disk label.
ics mode. Fore more, type graftabl /?".
Links:
Links:
label at ss64.com
graftabl at Microsoft

label at Microsoft

4.26 HELP

4.30 MODE

Shows command help.

A multi-purpose command to display device status, congure ports and devices, and more.

Examples:

Links:
help
Shows the list of Windows-supplied commands.
help copy

mode at ss64.com
mode at Microsoft

4.31 MORE

Shows the help for COPY command, also


Displays the contents of a le or les, one screen at a
available by typing copy /?".
time. When redirected to a le, performs some conversions, also depending on the used switches.
Links:

Examples:

help at ss64.com

more Test.txt

help at Microsoft

more *.txt

26

grep -i sought.*string Source.txt | more /p >Out.txt

net computer

Taking the output of a non-Windows grep


command that produces line breaks consisting
solely of LF character without CR character,
converts LF line breaks to CR-LF line breaks.
CR-LF newlines are also known as DOS line
breaks, Windows line breaks, DOS newlines,
Windows newlines, and CR/LF line endings,as
opposed to LF line breaks used by some other
operating systems.

net cong

In some setups, seems to output gibberish if


the input contains LF line breaks and tab characters at the same time.

net helpmsg

In some setups, for the conversion, /p may be


unneeded. Thus, more would convert the
line breaks even without /p.
more /t4 Source.txt >Target.txt
Converts tab characters to 4 spaces.
In some setups, tab conversion takes place automatically, even without the /t switch. If so,
it is per default to 8 spaces.

EXTERNAL COMMANDS

net continue
net le
net group
net help

net localgroup
net name
net pause
net print
net send
net session
net share

Switch /e:
The online documentation for more in Windows
XP and Windows Vista does not mention the switch.
The switch /e is mentioned in more /?" at least in
Windows XP and Windows Vista.
Per more /?", the switch is supposed to enable extended features listed at the end of more /?" help
such as showing the current row on pressing "=".
However, in Windows XP and Windows Vista, that
seems to be enabled by default even without /e.

net start
net statistics
net stop
net time
net use
net user
net view

Hypothesis: In Windows XP and Windows Vista, /e


does not do anything; it is present for compatibility Links:
reasons.
Links:

net at ss64.com
net at Microsoft

more at ss64.com
more at Microsoft, Windows XP

4.33 OPENFILES

more at Microsoft, Windows Server 2008, Windows Performs actions pertaining to open les, especially those
Vista
opened by other users over the network. The actions involve querying, displaying, and disconnecting. For more,
type openles /?".

4.32 NET

Links:
Provides various network services, depending on the
command used. Available variants per command:
net accounts

openles at ss64.com
openles at Microsoft

4.38

RUNDLL32

27

4.34 PING

4.38 RUNDLL32

Synopsys:

Runs a function available from a DLL. The available


DLLs and their functions dier among Windows versions.

PING /?

Examples:

PING address
PING hostname

rundll32 sysdm.cpl,EditEnvironmentVariables

Send ICMP/IP echo packets over the network to the


designated address (or the rst IP address that the designated hostname maps to via name lookup) and print all Links:
responses received.
Links:

In some Windows versions, opens the dialog


for editing environment variables.

rundll32 at ss64.com

ping at ss64.com

rundll at robvanderwoude.com

ping at Microsoft

dx21.com - lists rundll32 examples

4.35 RECOVER

4.39 SCHTASKS

Schedules a program to be run at a certain time, more


Recovers as much information as it can from damaged
powerful than AT.
les on a defective disk.
Links:
Links:
recover at ss64.com
recover at Microsoft

4.36 REPLACE

schtasks at ss64.com
schtasks at Microsoft

4.40 SETX

Like SET, but aecting the whole machine rather than


Replaces les in the destination folder with same-named the current console or process. Not available in Windows
les in the source folder.
XP; available in Windows Vista and later.
Links:
Links:
replace at ss64.com

setx at ss64.com

replace at Microsoft

setx at Microsoft, Windows Server 2008, Windows


Vista

4.37 ROBOCOPY
4.41 SHUTDOWN
(Not in XP) Copies les and folders. See also XCOPY
and COPY.
Shuts down a computer, or logs o the current user.
Links:

Links:

robocopy at ss64.com

shutdown at ss64.com

robocopy at Microsoft

shutdown at Microsoft

28

4.42 SORT

EXTERNAL COMMANDS

4.45 TASKKILL

Sorts alphabetically, from A to Z or Z to A. Cannot sort Ends one or more tasks.


numerically: if the input contains one integer per line,
Examples:
12 comes before 9.
Examples:

taskkill /IM AcroRd32.exe


Ends all process with the name
AcroRd32.exe"; thus, ends all open instances of Acrobat Reader. The name can be
found using tasklist.

sort File.txt
Outputs the sorted content of File.txt.
sort /r File.txt
Sorts in reverse order, Z to A.

tasklist | nd notepad
taskkill /PID 5792

dir /b | sort

Ends the process AKA task with process ID


(PID) of 5792; the assumption is you have
found the PID using tasklist.

Links:
sort at ss64.com

Links:

sort at Microsoft
taskkill at ss64.com

4.43 SUBST

taskkill at Microsoft

Assigns a drive letter to a local folder, displays current


4.46
assignments, or removes an assignment.
Examples:
subst p: .
Assigns p: to the currect folder.
subst
Shows all assignments previously made using
subst.

Lists tasks, including task name and process id (PID).


Examples:
tasklist | sort
tasklist | nd AcroRd
tasklist | nd /C chrome.exe
Displays the number of tasks named
chrome.exe, belonging to Google Chrome
browser.

subst /d p:
Removes p: assignment.
Links:

TASKLIST

Links:

subst at ss64.com

tasklist at ss64.com

subst at Microsoft

tasklist at Microsoft

4.44 SYSTEMINFO

4.47 TIMEOUT

Shows conguration of a computer and its operating sys- Waits a specied number of seconds, displaying the number of remaining seconds as time passes, allowing the user
tem.
to interrupt the waiting by pressing a key. Also known as
Links:
delay or sleep. Available in Windows Vista and later.
systeminfo at ss64.com
systeminfo at Microsoft

Examples:
timeout /t 5

4.49

WHERE
Waits for ve seconds, allowing the user to
cancel the waiting by pressing a key.

29

4.49 WHERE

Displays the location of a le, searching in the current directory and in the PATH by default. Does some of the job
Waits for ve seconds, ignoring user input of which command of some other operating systems.
other than Control + C.
Available on Windows 2003, Windows Vista, Windows

timeout /t 5 /nobreak

timeout /t 5 /nobreak >nul


As above, but with no output.
Workaround in Windows XP:
ping -n 6 127.0.0.1 >nul
Waits for ve seconds; the number after -n is
the number of seconds to wait plus 1.
Perl-based workaround in Windows XP, requiring Perl
installed:

7, and later; not available on Windows XP. An alternative


to be used with Windows XP is in the examples below.
Does not nd internal commands, as there are no dot exe
les for them to match.
Examples:
where nd
Outputs the location of the nd command,
possibly C:\Windows\System32\nd.exe.
for %i in (nd.exe) do @echo %~$PATH:i

perl -e sleep 5

Outputs the location of nd.exe on Windows


XP. The name has to include ".exe, unlike
with the where command.

Waits for 5 seconds.


Links:

where /r . Tasks*

timeout at ss64.com

Searches for les whose name matches


Task*" recursively from the current folder.
Similar to dir /b /s Tasks*"

timeout at Microsoft
How to wait in a batch script? at stackoverow.com
Sleeping in a batch le at stackoverow.com

4.48 TREE

Links:
where at ss64.com
Is there an equivalent of 'which' on windows?

Displays a tree of all subdirectories of the current directory to any level of recursion or depth. If used with /F
4.50
switch, displays not only subdirectories but also les.
Examples:
tree
tree /f
Includes les in the listing, in addition to directories.
tree /f /a

WMIC

Starts
Windows
Management
Instrumentation
Command-line. For more, type wmic /?".
Links:
wmic at ss64.com
wmic at Microsoft

As above, but uses 7-bit ASCII characters in- 4.51 XCOPY


cluding "+", "-" and \" to draw the tree.
Copies les and directories in a more advanced way than
A snippet of a tree using 8-bit ASCII characters:
COPY, deprecated in Windows Vista and later. Type
xcopy
/? to learn more, including countless options.
winevt Logs TraceFormat winrm
Examples:
A snippet of a tree using 7-bit ASCII characters:
+---winevt | +---Logs | \---TraceFormat +---winrm
Links:
tree at Microsoft

xcopy C:\Windows\system
Copies all les, but not les in
nested folders, from the source folder
(C:\Windows\system) to the current folder.

30

xcopy /s /i C:\Windows\system C:\Windows2\system


Copies all les and folders to any nesting
depth (via "/s) from the source folder
(C:\Windows\system) to C:\Windows2\system, creating Windows-2\system if it
does not exist (via "/i).
xcopy /s /i /d:09-01-2014 C:\Windows\system
C:\Windows-2\system
As above, but copies only les changed on 1
September 2014 or later. Notice the use of
the month-rst convention even if you are on
a non-US locale of Windows.
xcopy /L /s /i /d:09-01-2014 C:\Windows\system
C:\Windows-2\system
As above, but in a test mode via /L (list-only,
output-only, display-only). Thus, does not do
any actual copying, merely lists what would be
copied.
Links:
xcopy at ss64.com
xcopy at Microsoft

External links
Windows XP - Command-line reference A-Z at microsoft.com
Windows CMD Commands at ss64.com -- licensed under Creative Commons Attribution-NonCommercial-Share Alike 2.0 UK: England &
Wales, and thus incompatible with CC-BY-SA used
by Wikibooks
The FreeDOS HTML Help at fdos.org -- a hypertext help system for FreeDOS commands, written
in 2003/2004, available under the GNU Free Documentation License

EXTERNAL LINKS

31

Text and image sources, contributors, and licenses

6.1

Text

Windows Batch Scripting Source: http://en.wikibooks.org/wiki/Windows%20Batch%20Scripting?oldid=2757316 Contributors: Robert


Horning, Alsocal, Chuckhomann, Uncle G, Derbeth, Darklama, Whiteknight, Kernigh, Pcu123456789, MichaelFrey, Lutskovp, Az1568,
Thenub314, Erlyrisa, Runningfridgesrule, Remi, Recent Runes, Dan Polansky, Melab, Kayau, JackPotte, Tiptoety, Jason.Cozens, QuiteUnusual, Adrignola, Wendy.krieger, Novem Linguae, Avicennasis, Ajraddatz, Mattias.Campe, TBloemink, Albin77, Ellisun, Glaisher,
Syum90, Fishsticks, ECHinton and Anonymous: 68

6.2

Images

6.3

Content license

Creative Commons Attribution-Share Alike 3.0

You might also like