Windows Batch Scripting
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.
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 "/?".
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.
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.
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
2.1.2
Quoting
2.1.4 Redirection
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.
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
(...)
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.
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
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.
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:
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.
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.7
String processing
echo %a:~0,1%
Result: abc
echo %a:~1,1%
Result: bc
Testing substring containment:
2.9
Wildcards
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:
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.
2.9 Wildcards
Many commands accept le name wildcards--characters
that do not stand for themselves and enable matching of
a group of lenames.
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.
CHOICE command
Using type con >myle.txt, for which the multiline user input is terminated by user pressing Control
+ Z.
2.12 Functions
Links:
Wildcards at ss64
Using wildcard characters at Microsoft
2.13
Calculation
9
Uses the standard perecent notation for variable expansion.
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.
set /a n1=2+3,n2=4*7
set /a n1=n2=2
set /a num="255^127
set /a num=255^127
Alternative placement of quotation marks.
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:
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
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
CLS
3.8
CHDIR
A synonym of CD.
3.7
COLOR
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
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
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
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.
dir /a
dir /ah
Lists hidden les only.
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
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
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.
Examples:
exit
exit /b
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.
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
14
BUILT-IN COMMANDS
3.21
IF
15
3.21 IF
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
ftype at Microsoft
An example:
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.
goto at ss64.com
goto at Microsoft
16
BUILT-IN COMMANDS
3.24 MOVE
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.
Links:
if at ss64.com
if at Microsoft
3.22 MD
Creates a new directory or directories. Has a synonym
MKDIR; see also its antonym RD.
Examples:
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
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
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
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
3.29 PUSHD
3.30 RD
RENAME
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
rd /s Dir1
Links:
18
rem at ss64.com
rem at Microsoft
3.34 RMDIR
BUILT-IN COMMANDS
set
Displays a list of environment variables
3.37 SHIFT
set HOME
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
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 ..
3.42 VER
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
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:
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
AT
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:
cacls at ss64.com
cacls at Microsoft
4.5
CHCP
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:
chkntfs at Microsoft
compact at Microsoft
4.8
CHOICE
4.12 CONVERT
convert at ss64.com
convert at Microsoft
22
EXTERNAL COMMANDS
4.13 DEBUG
4.17 DOSKEY
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 at technet.microsoft.com
4.14 DISKCOMP
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
4.16 DISKPART
4.18 DRIVERQUERY
Shows and congures the properties of disk partitions.
Links:
diskpart at ss64.com
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
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
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
ndstr at Microsoft
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.
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
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
Examples:
help at ss64.com
more Test.txt
help at Microsoft
more *.txt
26
net computer
net cong
net helpmsg
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
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:
PING /?
Examples:
PING address
PING hostname
rundll32 sysdm.cpl,EditEnvironmentVariables
rundll32 at ss64.com
ping at ss64.com
rundll at robvanderwoude.com
ping at Microsoft
4.35 RECOVER
4.39 SCHTASKS
4.36 REPLACE
schtasks at ss64.com
schtasks at Microsoft
4.40 SETX
setx at ss64.com
replace at Microsoft
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
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
Links:
sort at ss64.com
Links:
sort at Microsoft
taskkill at ss64.com
4.43 SUBST
taskkill at Microsoft
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
perl -e sleep 5
where /r . Tasks*
timeout at ss64.com
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
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
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
6.1
Text
6.2
Images
6.3
Content license