Windows Batch Scripting - Wikibooks, Open Books For An Open World
Windows Batch Scripting - Wikibooks, Open Books For An Open World
Windows Batch
Scripting
This book describes and shows how to use the Microsoft-supplied command interpreter
cmd.exe and the associated commands, and how to write Windows batch scripts for the
interpreter. cmd.exe is the default interpreter on all Windows NT-based operating systems,
including Windows XP, Windows 7 and Windows 10.
Introduction
This book addresses 32-bit Windows commands applicable to modern versions of Windows
based on the Windows NT environment. It does not address commands that are specific to DOS
environments and to DOS-based operating systems, such as Windows 95, Windows 98, and
Windows Me, whose Microsoft-supplied command interpreters are in fact DOS programs, not
Win32 programs.
You can find out which version of Windows you are running using the VER command.
This book first describes using the Windows NT command interpreter, how it receives, parses,
and processes commands from users. Then it describes various commands available.
To obtain an extensive list of Windows commands and their short summaries, open the
command prompt on any Windows computer, and type help. To find 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 files for MS DOS and Windows command interpreter. Other subject terms include
"batch file programming", "batch file scripting", "Windows batch command", "Windows batch file",
"Windows command line", "Windows command prompt", and "Windows shell scripting".
Variable substitution
A command line is scanned for variable specifications, and any found are replaced with the
contents of those variables.
Quoting
Special characters can be quoted, to remove their special meanings.
Syntax
Command lines are developed into a sequence of commands according to a syntax.
Redirection
Redirection specifications are applied, and removed from the command line, before an
individual command in a sequence is executed.
Variable substitution
…
Command lines can contain variable specifications. These comprise a % character followed by a
name, followed by a second % character unless the name is a digit in 0 ... 9 or an asterisk *.
%varname%, such as %PATH% or %USERNAME%, is replaced with the value of the named
environment variable. For example, %PATH% is replaced by the value of the PATH environment
variable.
%n for 0 <= n <= 9, such as %0 or %9, is replaced with the value of the n-th parameter passed
to the batch file when it was invoked, subject to any subsequent modifications by the SHIFT
command. For example: %2 is replaced by the value of the second batch file parameter.
%* is replaced with the values of all the command-line parameters except for %0, even those
beyond index 9. SHIFT command has no impact on the result of %*. See also Command-line
arguments.
Special names
E…
Some variable names are not visible using SET command. Rather, they are made available for
reading using the % notation. To find out about them, type "help set".
Links:
You can place caret (^), an escape character, immediately before the special characters. In a
command located after a pipe (|), you need to use three carets (^^^) for this to work.
The special characters that need quoting or escaping are usually <, >, |, &, and ^. In some
circumstances, ! and \ may need to be escaped. A newline can be escaped using caret as well.
When you surround the string using quotation marks, they become part of the argument passed
to the command invoked. By contrast, when you use caret as an escape character, the caret
does not become part of the argument passed.
The percent sign (%) is a special case. On the command line, it does not need quoting or
escaping unless two of them are used to indicate a variable, such as %OS%. But in a batch file,
you have to use a double percent sign (%%) to yield a single percent sign (%). Enclosing the
percent sign in quotation marks or preceding it with caret does not work.
Examples
echo A ^^ B
Echoes A ^ B. Caret needs escaping as well or else it is interpreted as escaping a space.
if 1 equ 1 ^
echo Equal &^
echo Indeed, equal
Echoes the two strings. The caret at the end of the line escapes the newlines, leading to
the three lines being treated as if they were a single line. The space before the first caret
is necessary or else 1 gets joined with the following echo to yield 1echo.
set /a modulo=14%%3
If run from a batch, sets modulo variable to 2, the remainder of dividing 14 by 3. Does not
work with single %.
echo %temp%
Outputs the content of temp variable even if run from a batch file. Use of the percent sign
in a batch to access environment variables and passed arguments needs no escaping.
echo ^%temp^%
Outputs literally %temp% when run from the command line.
echo %%temp%%
Outputs literally %temp% when run from a batch.
Links:
set (https://docs.microsoft.com/en-us/windows-server/administration/windows-command
s/set_1) at Microsoft
Syntax
…
Command lines are developed into a sequence of commands according to a syntax. In that
syntax, simple commands may be combined to form pipelines, which may in turn be combined to
form compound commands, which finally may be turned into parenthesized commands.
A simple command is just a command name, a command tail, and some redirection
specifications. An example of a simple command is dir *.txt > somefile.
A pipeline is several simple commands joined together with the "pipe" metacharacter—"|", also
known as the "vertical bar". The standard output of the simple command preceding each vertical
bar is connected to the standard input of the simple command following it, via a 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 | more.
The conjunctions:
& - An unconditional conjunction. The next pipeline is always executed after the current one
has completed executing.
&& - A positive conditional conjunction. The next pipeline is executed if the current one
completes executing with a zero exit status.
|| - A negative conditional conjunction. The next pipeline is executed if the current one
completes executing with a non-zero exit status.
A parenthesized command is a compound command enclosed in parentheses (i.e. ( and )). From
the point of view of syntax, this turns a compound command into a simple command, whose
overall output can be redirected.
For example: The command line ( pushd temp & dir & popd ) > somefile causes the standard
output of the entire compound command ( pushd temp & dir & popd ) to be redirected to
somefile.
Links:
< filename
Redirect standard input to read from the named file.
> filename
Redirect standard output to write to the named file, overwriting its previous contents.
>> filename
Redirect standard output to write to the named file, appending to the end of its previous
contents.
>&h
Redirect to handle h, where handle is any of 0—standard input, 1—standard output, 2—
standard error, and more.
<&h
Redirect from handle h.
Examples:
Links:
Batch reloading
…
The command interpreter reloads the content of a batch after each execution of a line or a
bracketed group.
If you start the following batch and change "echo A" to "echo B" in the batch shortly after starting
it, the output will be B.
@echo off
ping -n 6 127.0.0.1 >nul & REM wait
echo A
What is on a single line does matter; changing "echo A" in the following batch after running it has
no impact:
@echo off
ping -n 6 127.0.0.1 >nul & echo A
Nor have after-start changes have any impact on commands bracketed with ( and ). Thus,
changing "echo A" after starting the following batch has no impact:
@echo off
for /L %%i in (1,1,10) do (
ping -n 2 127.0.0.1 >nul & REM wait
echo A
)
@echo off
(
ping -n 6 127.0.0.1 >nul & REM wait
echo A
)
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 affected by the SET, PATH, and PROMPT commands.
Command interpreters generally have textual user interfaces, not graphical ones, and so do not
recognize the Windows message that informs applications that the environment variable
template in the Registry has been changed. Changing the environment variables in Control Panel
will cause Windows Explorer to update its own environment variables from the template in the
Registry, and thus change the environment variables that any subsequently invoked command
interpreters will inherit. However, it will not cause command interpreters that are already running
to update their environment variables from the template in the Registry.
COMSPEC
…
The COMSPEC environment variable contains the full pathname of the command interpreter
program file. 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.
PATH
…
The value of the PATH environment variable comprises a list of directory names, separated by
semi-colon characters. This is the list of directories that are searched, in order, when locating the
program file of an external command to execute.
PATHEXT
…
The value of the PATHEXT environment variable comprises a list of filename extensions,
separated by semi-colon characters. This is the list of filename extensions that are applied, in
order, when locating the program file of an external command to execute.
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
By adding ".PL" to the variable, you can ensure Perl programs get run from the command line
even when typed without the ".pl" extension. Thus, instead of typing "mydiff.pl a.txt b.txt", you
can type "mydiff a.txt b.txt".
Links:
Making Python scripts run on Windows without specifying “.py” extension at stackoverflow (ht
tp://stackoverflow.com/questions/9037346/making-python-scripts-run-on-windows-without-s
pecifying-py-extension)
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 file line in batch file 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:
Characters Expansion Result
$$ $ character itself
& symbol AKA ampersand. A convenience, since it is difficult to place a literal & in
$A
the value of the PROMPT environment variable using the SET command.
$B Vertical bar '|' (pipe symbol)
$C Left parenthesis '('
$D Current date
$E ESC (ASCII code 27)
$F Right parenthesis ')'
$G Greater-than symbol '>'
$H Backspace (deletes previous character)
$L Less-than symbol '<'
Remote name linked to the current drive if it is a network drive; empty string
$M
otherwise.
$N Current drive letter
$P Current drive letter and full path
$Q '=' (equals sign)
$S ' ' (space character)
$T Current system time
$V Windows version number
$_ <CR> (carriage return character, aka "enter")
$+ As many plus signs (+) as there are items on the pushd directory stack
Links:
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 case-sensitivity.
Examples:
dir /?
Displays the help. This option is provided by many commands.
dir /b /s
Lists all files 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.
dir/b/s
Works. In dir, removing whitespace between the command and the first switch or between
the switches does not make a difference; 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
find/i/v work.
dir /od
The switch letter o is further modified 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 file.txt
Sorts the file in a reverse order.
sort /reverse file.txt
Sort allows the switch string to be longer than a single-letter.
java -version
Java, which originated in the environment of another operating system family, uses the
minus convention for its switches AKA options.
grep --help
If GNU grep is installed, it requires multi-letter switches to be preceded by two dashes.
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.
0 - success
not 0 - failure
If the command does not distinguish various kinds of failure, the error level on failure is
usually 1.
Examples:
dir >NUL && echo Success
The part after && is executed only if the error level is zero.
color 00 || (
echo Failure
)
Multiline bracketing works as well.
echo %ERRORLEVEL%
Displays the error level without changing it.
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.
exit /b 1
Returns a batch file, setting the error level to 1.
(cmd /c "exit /b 0" && Echo Success) & (cmd /c "exit /b -1" || Echo Failure)
As above, showing the error level is indeed affected.
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:
String processing
…
Getting a substring of a non-empty variable:
set a=abcdefgh
echo %a:~0,1% & rem from index 0, length 1; result: a
echo %a:~1,1% & rem from index 1, length 1; result: b
echo %a:~0,2% & rem from index 0, length 2; result: ab
echo %a:~1,2% & rem from index 1, length 2; result: bc
echo %a:~1% & rem from index 1 to the end; result: bcdefgh
echo %a:~-1% & rem from index -1 (last char) to the end; result:
h
echo %a:~-2% & rem from index -2 (next-to-last) to the end;
result: gh
echo %a:~0,-2% & rem from index 0 to index -2, excl.; result:
abcdef
echo %a:~0,-1% & rem from index 0 to index -1, excl.; result:
abcdefg
echo %a:~1,-1% & rem from index 1 to index -1, excl.; result:
bcdefg
This test does not work if the variable contains a quotation mark.
String replacement:
set a=abcd & echo %a:c=% & rem replace c with nothing; result:
abd
set a=abcd & echo %a:c=e% & rem replace c with e; result: abed;
set a=abcd & echo %a:*c=% & rem replace all up to c with nothing;
result: d
rem Above, the asterisk (*) only works at the beginning of the
sought pattern.
Splitting a string by any of " ", "," and ";": ["space", "comma" and "semicolon":]
@echo off
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
Limitations:
The above string processing does not work with parameter variables (%1, %2, ...).
Links:
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
file.
Testing for whether the first command-line argument has been provided:
A robust looping over all command-line arguments using SHIFT (for each command-line
argument, ...):
:argactionstart
if -%1-==-- goto argactionend
echo %1 & REM Or do any other thing with the argument
shift
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 unmodified 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
setlocal EnableDelayedExpansion
REM Prevent affecting 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
set argcount=0
for %%i in (%*) do set /a argcount+=1
The maximum possible number of arguments is greater than 4000, as empirically determined on
a Windows Vista machine. The number can differ on Windows XP and 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
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.
When passing arguments to an invoked command rather than a batch script, you usually need to
separate the command from the first argument using a space. However, for internal commands,
that separation is not necessary if the first character after the command name is one of a couple
of symbols, including .\/, and more:
echo.
Outputs a newline.
tree.
Fails: "tree." not found. tree is an external command.
dir..
Lists the content of the parent directory.
cd..
Changes the current directory to the parent one.
cd\
Changes the current directory to the root one.
start.
Opens Windows Explorer from the current directory.
dir/b/s
Lists directory content recursively, showing full paths.
Links:
Wildcards
…
Many commands accept file name wildcards--characters that do not stand for themselves and
enable matching of a group of filenames.
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 file name, possibly zero number
of characters; see examples for clarification
Examples:
dir *.txt
Matches Myfile.txt, Plan.txt and any other file with the .txt extension.
dir *txt
The period does not need to be included. However, this will also match files named
without the period convention, such as myfiletxt.
dir a?b.txt
Matches files 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
Matches .txt, a.txt, aa.txt, and aaa.txt, among others, since each question mark in the
sequence followed by a period can match zero number of characters.
dir a???.b???.txt???
Matches a.b.txt, among others. While the last question mark sequence is not followed by
a period, it is still a sequence at the end of a maximum period-free part of a file name.
Quirk with short file names: the wildcard matching is performed both on long file names and the
usually hidden short 8 chars + period + 3 chars file names. This can lead to bad surprises.
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 file 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 files matching the wildcard. Thus, "echo *.txt" does not display files in the
current folder matching the pattern but rather literally displays "*.txt". Another consequence is
that you can write "findstr a.*txt" without fearing that the "a.*txt" part gets replaced with the
names of some files in the current folder. Furthermore, recursive "findstr /s pattern *.txt" is
possible, while in some other operating systems, the "*.txt" part would get replaced with the file
names found in the current folder, disregarding nested folders.
Commands accepting wildcards include ATTRIB, COPY, DIR, FINDSTR, FOR, REN, etc.
Links:
User input
…
You can get input from the user using the following methods:
SET /P command
CHOICE command
Using "type con >myfile.txt", for which the multi-line user input is terminated by user pressing
Control + Z.
Percent tilde
…
When a command-line argument contains a file name, special syntax can be used to get various
information about the file.
The following syntaxes expand to various information about the file passed as %1:
Syntax Expansion Result Example
%~1 %1 with no enclosing quotation marks Not provided
%~f1 Full path with a drive letter C:\Windows\System32\notepad.exe
%~d1 Drive letter C:
%~p1 Drive-less path with the trailing backslash \Windows\System32\
For a file, the file name without path and
extension
%~n1 notepad
For a folder, the folder name
The same syntax applies to single-letter variables created by FOR command, such as "%%i".
To learn about this subject from the command line, type "call /?" or "for /?".
Links:
Functions
…
Functions AKA subprograms can be emulated using CALL, labels, SETLOCAL and ENDLOCAL.
@echo off
call :power 2 4
echo %result%
rem Prints 16, determined as 2 * 2 * 2 * 2
goto :eof
While the goto :eof at the end of the function is not really needed, it has to be there in the general
case in which there is more than one function.
The variable into which the result should be stored can be specified on the calling line as
follows:
@echo off
call :sayhello result=world
echo %result%
exit /b
:sayhello
set %1=Hello %2
REM Set %1 to set the returning value
exit /b
In the example above, exit /b is used instead of goto :eof to the same effect.
Also, remember that the equal sign is a way to separate parameters. Thus, the following items
achieve the same:
Links:
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 is -2147483648 = - (2 ^ 31), assignable with the trick of set /a num=-2147483647-1. The
syntax is reminiscent of the C language.
A logical operator of negation is !: it turns zero into one and non-zero into zero.
Combined assignment operators are modeled on "+=", which, in "a+=b", means "a=a+b". Thus, "a-
=b" means "a=a-b". Similarly for *=, /=, %=, &=, ^=, |=, <<=, and >>=.
1. ( )
2. * / % + -
3. << >>
4. &
5. ^
6. |
8. ,
Literals can be entered as decimal (1234), hexadecimal (0xffff, leading 0x), and octal (0777,
leading 0).
The internal bit representation of negative numbers is two's complement. This provides a
connection between arithmetic operations and bit operations. For instance, -2147483648 is
represented as 0x80000000, and therefore set /a num=~(-2147483647-1) yields 2147483647,
which equals 0x7FFFFFFF (type set /a num=0x7FFFFFFF to check).
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:
set /a num="255^127"
set /a "num=255^127"
Alternative placement of quotation marks.
set /a num=255^^127
Escape ^ using ^ instead of quotation marks.
Examples:
set /a n3=%n1%+%n2%
set /a n3=n1+n2
Avoids the percent notation around variable names as unneeded for /a.
set /a num="255^127"
Encloses "^" in quotation marks to prevent its special meaning for the command
interpreter.
set /a n1=2+3,n2=4*7
Performs two calculations.
set /a n1=n2=2
Has the same effect as n1=2,n2=2.
set /a n1=2,n2=3,n3=n1+n2
Works as expected.
set /a n1=0xffff
Sets n1 using hexadecimal notation.
set /a n1=0777
Sets n1 using octal notation.
set /a n1=%random%
A pseudo-random number from 0 to 32767 = 2^15-1.
set /a n1="%random%>>10"
A pseudo-random number from 0 to 31 = 2^5-1. The shift right operator drops 10 out of 15
bits, keeping 5 bits.
set /a n1=%random%%50
A pseudo-random number from 0 to 49. Uses the % modulo operator. In a batch, %% is
needed for modulo: set /a n1=%random%%%50. Because of this particular use of the
modulo, the result is not perfectly uniform; it is uniform if the 2nd modulo operand--above
50--equals to a power of 2, e.g. 256 = 2^8.
set /a n1="(%random%<<15)+%random%"
A pseudo-random number from 0 to 1073741823 = 2^30 - 1. Combines the two 15-bit
random numbers produced by %random% alone to produce a single 30-bit random
number..
set /a n1="((%random%<<15)+%random%)%1000000"
As above, but again using modulo, this time to achieve the range 0 to 999999.
@echo off
setlocal
set n=1
:print_primes_loop
set /a n=n+1
set cand_divisor=1
:print_primes_loop2
set /a cand_divisor=cand_divisor+1
set /a cand_divisor_squared=cand_divisor*cand_divisor
if %cand_divisor_squared% gtr %n% echo Prime %n% & goto
:print_primes_loop
set /a modulo=n%%cand_divisor
if %modulo% equ 0 goto :print_primes_loop & REM Not a prime
goto :print_primes_loop2
Links:
Finding files
…
Files can be found using #DIR, #FOR, #FINDSTR, #FORFILES, and #WHERE.
Examples:
dir /b /s *base*.doc*
Outputs all files in the current folder and its subfolders such that the file name before the
extension contains the word "base" and whose extension starts with "doc", which includes
"doc" and "docx". The files are output with full paths, one file per line.
where *.bat
Outputs all .bat files in the current directory and in the directories that are in PATH.
Keyboard shortcuts
…
When using Windows command line from the standard console that appears after typing
cmd.exe after pressing Windows + R, you can use multiple keyboard shortcuts, including
function keys:
Tab: Completes the relevant part of the typed string from file names or folder names in the
current folder. The relevant part is usually the last space-free part, but use of quotation marks
changes that. Generally considers both files and folders for completion, but cd command only
considers folders.
Up and down arrow keys: Enters commands from the command history, one at a time.
F1: Types the characters from the single previously entered command from the command
history, one character at a time. Each subsequent press of F1 enters one more character.
F2: Asks you to type a character, and enters the shortest prefix of the previous command from
the command history that does not include the typed character. Thus, if the previous
command was echo Hello world and you typed o, enters ech.
F3: Enters the single previous command from the command history. Repeated pressing has no
further effect.
F4: Asks you to type a character, and erases the part of the currently typed string that starts at
the current cursor location, continues to the right, and ends with the character you entered
excluding that character. Thus, if you type echo Hello world, place the cursor at H using left
arrow key, press F4 and then w, you get echo world. If you press F4 and then Enter, erases the
text from the cursor to the end of the line.
F5: Enters previous commands from the command history, one at a time.
F7: Opens a character-based popup window with the command history, and lets you use arrow
key and enter to select a command. After you press enter in the popup, the command is
immediately executed.
F8: Given an already typed string, shows items from the command history that have that string
as a prefix, one at a time.
F9: Lets you enter the number of the command from the command history, and then executes
the command.
The availability of the above shortcuts does not seem to depend on running DOSKEY.
Links:
Paths
…
File and directory paths follow certain conventions. These include the possible use of a drive
letter followed by a colon (:), the use of backslash (\) as the path separator, and the distinction
between relative and absolute paths.
Forward slash (/) often works when used instead of (\) but not always; it is normally used to
mark switches (options). Using forward slash can lead to various obscure behaviors, and is best
avoided.
Special device names include NUL, CON, PRN, AUX, COM1, ..., COM9, LPT1, ..., LPT9; these can
be redirected to.
Examples:
attrib C:\Windows\System32\notepad.exe
Succeeds if the file exists, as it should. This is an absolute path with a drive letter. It is
also known as a fully qualified path.
attrib \Windows\System32\notepad.exe
Succeeds if the current drive is C:, and if the file exists, as it should. This is an absolute
path without a drive letter.
attrib .
A single period denotes the current folder.
cd C:\Windows\System32\
Succeeds, whyever.
cd ..
A double period denotes the parent folder.
attrib C:\Windows\System32\..\..\Windows\System32
A double period can be used in the middle of the path to navigate to the parent folder,
even multiple times.
attrib \\myserver\myvolume
A network UNC path starts with double backslash and no drive letter.
cd \\myserver\myvolume
Does not work; changing to a server folder in this direct manner does not work.
pushd \\myserver\folder
Automatically creates a drive for the folder and changes to it. After you use #POPD, the
drive gets unassigned again.
attrib C:/Windows/System32/notepad.exe
Succeeds on multiple versions of cmd.exe. Uses forward slashes.
Links:
Why does the cmd.exe shell on Windows fail with paths using a forward-slash ('/) path
separator? (http://stackoverflow.com/questions/10523708/why-does-the-cmd-exe-shell-on-wi
ndows-fail-with-paths-using-a-forward-slash) , stackoverflow.com
Arrays
…
Arrays can be emulated in the delayed expansion mode using the combination of % and ! to
indicate variables. There, %i% is the value of variable i with the immediate expansion while !i! is
the value of variable i in the delayed expansion.
@echo off
setlocal EnableDelayedExpansion
for /l %%i in (1, 1, 10) do (
set array_%%i=!random!
)
for /l %%i in (1, 1, 10) do (
echo !array_%%i!
)
Links:
Arrays, linked lists and other data structures in cmd.exe (batch) script (http://stackoverflow.co
m/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/
10167990#10167990) , stackoverflow.com
Perl one-liners
…
Some tasks can be conveniently achieved with Perl one-liners. Perl is a scripting language
originating in the environment of another operating system. Since many Windows computing
environments have Perl installed, Perl one-liners are a natural and compact extension of
Windows batch scripting.
Examples:
for /f %i in ('perl -MPOSIX -le "print strftime '%Y-%m-%d', localtime"') do @set isodate=%i
Gets current date in the ISO format into isodate variable.
On the web, Perl one-liners are often posted in the command-line conventions of another
operating system, including the use of apostrophe (') to surround the arguments instead of
Windows quotation marks. These need to be tweaked for Windows.
Links:
W:One-liner program#Perl
Unix commands
…
Windows cmd.exe command interpreter can use commands from Unix-like operating systems,
provided they are installed. Example commands include grep, sed, awk, wc, head and tail. The
commands are available from GNU project, and their Windows ports exist. You can learn more
about the commands in Guide to Unix Wikibook. Beware that batch programs that come to
depend on these commands are not guaranteed to work on other Windows machines.
Freely licensed Windows versions of GNU commands can be obtained from the following
projects:
An alternative way of running GNU commands for Windows 10 is Windows Subsystem for Linux.
Limitations
…
There is no touch command familiar from other operating systems. The touch command would
modify the last-modification timestamp of a file without changing its content.
One workaround, with unclear reliability and applicability across various Windows versions, is
this:
copy /b file.txt+,,
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.
Overview …
Command Description
ASSOC Associates an extension with a file type (FTYPE).
BREAK Sets or clears extended CTRL+C checking.
CALL Calls one batch program from another.
CD, CHDIR Displays or sets the current directory.
CHCP Displays or sets the active code page number.
CLS Clears the screen.
COLOR Sets the console foreground and background colors.
COPY Copies files.
DATE Displays and sets the system date.
DEL, ERASE Deletes one or more files.
DIR Displays a list of files and subdirectories in a directory.
ECHO Displays messages, or turns command echoing on or off.
ELSE Performs conditional processing in batch programs when "IF" is not true.
ENDLOCAL Ends localization of environment changes in a batch file.
EXIT Quits the CMD.EXE program (command interpreter).
FOR Runs a specified command for each file in a set of files.
FTYPE Sets the file type command.
GOTO Goes to a label.
IF Performs conditional processing in batch programs.
MD, MKDIR Creates a directory.
MOVE Moves a file to a new location
PATH Sets or modifies the PATH environment
PAUSE Causes the command session to pause for user input.
POPD Changes to the drive and directory popped from the directory stack
PROMPT Sets or modifies the string displayed when waiting for input.
PUSHD Pushes the current directory onto the stack, and changes to the new directory.
RD / RMDIR Removes the directory.
REM A comment command. Unlike double-colon (::), the command can be executed.
REN / RENAME Renames a file or directory
SET Sets or displays shell environment variables
SETLOCAL Creates a child-environment for the batch file.
SHIFT Moves the batch parameters forward.
START Starts a program with various options.
TIME Displays or sets the system clock
TITLE Changes the window title
TYPE Prints the content of a file to the console.
VER Shows the command processor, operating system versions.
VERIFY Verifies that file copy has been done correctly.
VOL Shows the label of the current volume.
ASSOC
…
Associates an extension with a file type (FTYPE), displays existing associations, or deletes an
association. See also FTYPE.
Examples:
assoc
Lists all associations, in the format "<file extension>=<file type>", as, for example,
".pl=Perl" or ".xls=Excel.Sheet.8".
Links:
Making Python scripts run on Windows without specifying “.py” extension at stackoverflow (ht
tp://stackoverflow.com/questions/9037346/making-python-scripts-run-on-windows-without-s
pecifying-py-extension)
BREAK
…
In Windows versions based on Windows NT, does nothing; kept for compatibility with MS DOS.
Examples:
Links:
CALL
…
Calls one batch program from another, calls a subprogram within a single batch program, or, as
an undocumented behavior, starts a program. In particular, suspends the execution of the caller,
starts executing the callee, and resumes the execution of the caller if and when the callee
finishes execution.
Beware that calling a batch program from a batch without using the call keyword results in the
execution never returning to the caller once the callee finishes.
The callee inherits environment variables of the caller, and unless the callee prevents that via
SETLOCAL, changes made by the callee to environment variables become visible to the caller
once it resumes execution.
Examples:
mybatch.bat
If used in a batch, transfers control to mybatch.bat and never resumes the execution of
the caller.
call mybatch.bat
call mybatch
call :mylabel
cmd /c mybatch.bat
Similar to call, but resumes execution even when there are errors. Furthermore, any
changes the callee makes to environment variables are not propagated to the caller.
call notepad.exe
Launches Notepad, or in general, any other executable. This is apparently not the intended
usage of call, and is not officially documented.
Links:
CD
…
Changes to a different directory, or displays the current directory. However, if a different drive
letter is used, it does not switch to that different drive or volume.
Examples:
cd
Outputs the current directory, e.g. C:\Windows\System32.
cd C:\Program Files
No surrounding quotes are needed around paths with spaces.
cd \Program Files
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.
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 tree up and down
cd \\myserver\folder
Does not work. Changing the directory directly to a network Universal Naming Convention
(UNC) folder does not work. Keywords: UNC path.
pushd \\myserver\folder
Automatically creates a drive for the folder and changes to it. After you use #POPD, the
drive gets unassigned again.
cd C:\W*
Changes to C:\Windows, in a typical Windows setup. Thus, wildcards work. Useful for
manual typing from the command line.
cd C:\W*\*32
Changes to C:\Windows\System32, in a typical Windows setup.
Links:
cd at ss64.com (https://ss64.com/nt/cd.html)
cd at Microsoft (https://docs.microsoft.com/en-us/windows-server/administration/windows-c
ommands/cd)
CHDIR
…
A synonym of CD.
CLS
…
Clears the screen.
COLOR …
Sets the console foreground and background colors.
Examples:
color f9
Use white background and blue foreground.
color
Restore the original color setting.
Links:
COPY
…
Copies files. See also MOVE, XCOPY and ROBOCOPY.
Examples:
copy F:\File.txt
Copies the file into the current directory, assuming the current directory is not F:\.
copy F:\*.txt
Copies the files located at F:\ and ending in dot txt into the current directory, assuming
the current directory is not F:\.
copy F:\*.txt .
Does the same as the above command.
copy File.txt
Issues an error message, as File.txt cannot be copied over itself.
Links:
DEL
…
Deletes files. Use with caution, especially in combination with wildcards. Only deletes files, not
directories, for which see RD. For more, type "del /?".
Examples:
del File.txt
del /s *.txt
Deletes the files recursively including nested directories, but keeps the directories;
mercilessly deletes all matching files without asking for confirmation.
del /p /s *.txt
As above, but asks for confirmation before every single file.
del /q *.txt
Deletes without asking for confirmation.
Links:
DIR
…
Lists the contents of a directory. Offers a range of options. Type "dir /?" for more help.
Examples:
dir
Lists the files and folders in the current folder, excluding hidden files and system files;
uses a different manner of listing if DIRCMD variable is non-empty and contains switches
for dir.
dir D:
dir /b C:\Users
dir /s
Lists the contents of the directory and all subdirectories recursively.
dir /s /b
Lists the contents of the directory and all subdirectories recursively, one file per line,
displaying complete path for each listed file or directory.
dir *.txt
Lists all files with .txt extension.
dir /a
Includes hidden files and system files in the listing.
dir /ah
Lists hidden files 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 files only, omitting directories.
dir /a-d-h
Lists non-hidden files only, omitting directories.
dir /od
Orders the files and folders by the date of last modification. Other letters after /O include
N (by name), E (by extension), S (by size), and G (folders first)
dir /o-s
Orders the files by the size descending; the impact on folder order is unclear.
dir /s /b /od
Lists the contents of the directory and all subdirectories recursively, ordering the files in
each directory by the date of last modification. The ordering only happens per directory;
the complete set of files so found is not ordered as a whole.
dir /a /s
Lists files recursively including hidden files and system files. Can be used to find out the
disk usage (directory size), by considering the final lines of the output.
Links:
DATE
…
Displays or sets the date. The way the date is displayed depends on country settings. Date can
also be displayed using "echo %DATE%".
Getting date in the iso format, like "2000-01-28": That is nowhere easy, as the date format
depends on country settings.
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%
To use the above in a batch, turn %i into %%i and remove @ from before if.
Links:
How to get current datetime on Windows command line, in a suitable format for using in a
filename? (http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windo
ws-command-line-in-a-suitable-format-for-us) at stackoverflow
ECHO
…
Displays messages, or turns command echoing on or off.
Examples:
echo on
@echo off
echo Hello
echo "hello"
Displays the quotes too.
echo %PATH%
Displays the contents of PATH variable.
echo.
Outputs a newline while the period is not being output. Without the period, outputs "echo
off" or "echo on". Adding a space before the period leads to the period being output. Other
characters having the same effect as period include :;,/\(=+[].
echo %random%>>MyRandomNumbers.txt
While it seems to output random numbers to MyRandomNumbers.txt, it actually does not
do so for numbers 0-9, since these, when placed before >>, indicate which channel is to
be redirected. See also #Redirection.
echo 2>>MyRandomNumbers.txt
Instead of echoing 2, redirects standard error to the file.
(echo 2)>>MyRandomNumbers.txt
Echoes even a small number (in this case 2) and redirects the result.
>>MyRandomNumbers.txt echo 2
Another way to echo even a small number and redirect the result.
Links:
ELSE
…
An example:
if exist file.txt (
echo The file exists.
) else (
echo The file does not exist.
)
ENDLOCAL
…
Ends local set of environment variables started using SETLOCAL. Can be used to create
subprograms: see Functions.
Links:
ERASE
…
A synonym of DEL.
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 file, causes the DOS console calling the batch to close.
Examples:
exit
exit /b
Links:
FOR
…
Iterates over a series of values, executing a command.
In the following examples, %i is to be used from the command line while %%i is to be used from
a batch. The index (e.g., %i) must be a single character variable name.
Examples:
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.
The for command tries to interpret the items as file names and as patterns of file names
containing wildcards.
It does not complain if the items do not match existing file names, though.
The two consecutive colons are treated as one separator; %c is not "" but rather "Third".
Does some of the job of the cut command from other operating systems.
Continue: To jump to the next iteration of the loop and thus emulate the continue statement
known from many languages, you can use goto provided you put the loop body in a subroutine,
as shown in the following:
for %%i in (a b c) do call :for_body %%i
exit /b
:for_body
echo 1 %1
goto :cont
echo 2 %1
:cont
exit /b
If you use goto directly inside the for loop, the use of goto breaks the loop bookkeeping. The
following fails:
for %%i in (a b c) do (
echo 1 %%i
goto :cont
echo 2 %%i
:cont
echo 3 %%i
)
Links:
FTYPE
…
Displays or sets the command to be executed for a file type. See also ASSOC.
Examples:
ftype
Lists all associations of commands to be executed with file types, as, for example,
'Perl="C:\Perl\bin\perl.exe" "%1" %*'
Links:
Making Python scripts run on Windows without specifying “.py” extension at stackoverflow (ht
tp://stackoverflow.com/questions/9037346/making-python-scripts-run-on-windows-without-s
pecifying-py-extension)
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 file.
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
…
Conditionally executes a command. Documentation is available by entering IF /? to CMD prompt.
exist <filename>
<string>==<string>
defined <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.
An example:
Examples:
if "/i"=="/i" echo Equal, using quotation marks to prevent the literal meaning of /i
Links:
if at ss64.com (https://ss64.com/nt/if.html)
if at Microsoft (https://docs.microsoft.com/en-us/windows-server/administration/windows-c
ommands/if)
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.
md Dir1 Dir2
Creates two directories in the current directory.
md at ss64.com (https://ss64.com/nt/md.html)
md at Microsoft (https://docs.microsoft.com/en-us/windows-server/administration/windows-
commands/md)
MKDIR
…
A synonym for MD.
MKLINK
…
Makes a symbolic link or other type of link. Available since Windows Vista.
Links:
MOVE
…
Moves files or directories between directories, or renames them. See also REN.
Examples:
move F:\File.txt
Moves the file to the current directory.
move F:\*.txt
Moves the files located at F:\ and ending in dot txt into the current directory, assuming the
current directory is not F:\.
Links:
PATH
…
Outputs or sets the value of the PATH environment variable. When outputing, includes "PATH="
at the beginning of the output.
Examples:
path
Outputs the PATH. An example output:
PATH=C:\Windows\system32;C:\Windows;C:\Program Files\Python27
path ;
Empties the path.
Links:
PAUSE
…
Prompts the user and waits for a line of input to be entered.
Links:
POPD
…
Changes to the drive and directory popped from the directory stack. The directory stack is filled
using the PUSHD command.
Links:
PROMPT
…
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>CD
C:\
MyPrompt>PROMPT
C:\>
The PROMPT command is used to set the prompt to "MyPrompt>". The CD shows that the
current directory path is "C:\". Using PROMPT without any parameters sets the prompt back to
the directory path.
Links:
PUSHD
…
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 directory stated as the argument.
Links:
RD
…
Removes directories. See also its synonym RMDIR and antonym MD. Per default, only empty
directories can be removed. Also type "rd /?".
Examples:
rd Dir1
rd Dir1 Dir2
rd /s Dir1
Removes the directory Dir1 including all the files and subdirectories in it, asking for
confirmation once before proceeding with the removal. To delete files recursively in
nested directories with a confirmation per file, use DEL with /s switch.
rd /q /s Dir1
Like above, but without asking for confirmation.
Links:
rd at ss64.com (https://ss64.com/nt/rd.html)
rd at Microsoft (https://docs.microsoft.com/en-us/windows-server/administration/windows-c
ommands/rd)
REN
…
Renames files and directories.
Examples:
Links:
RENAME
…
This is a synonym of REN command.
REM
…
Used for remarks in batch files, preventing the content of the remark from being executed.
An example:
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.
Double colon is an alternative to REM. It can cause trouble when used in the middle of
sequences in parentheses, like those used in FOR loops. The double colon seems to be just a
trick, a label that starts with a colon.
Links:
RMDIR
…
This is a synonym of RD.
SET
…
Displays or sets environment variables. With /P switch, it asks the user for input, storing the
result in the variable. With /A switch, it performs simple arithmetic calculations, storing the
result in the variable. With string assignments, there must be no spaces before and after the
equality sign; thus, "set name = Peter" does not work, while "set name=Peter" does.
Examples:
set
Displays a list of environment variables
set HOME
Displays the values of the environment variables whose names start with "HOME"
set MYNUMBER=56
set /A result = 4 * ( 6 / 3 )
Sets the result variable with the result of a calculation. See also #Calculation.
Links:
SETLOCAL
…
When used in a batch file, makes all further changes to environment variables local to the
current batch file. When used outside of a batch file, does nothing. Can be ended using
ENDLOCAL. Exiting a batch file automatically calls "end local". Can be used to create
subprograms: see Functions.
The following is an example of using delayed expansion in a script that prints the specified
number of first lines of a file, providing some of the function of the command "head" known from
other operating systems:
@echo off
:: Function myhead
:: ===============
:: %1 - lines count, %2 - file name
:myhead
setlocal EnableDelayedExpansion
set counter=1
for /f "tokens=*" %%i in (%2) do (
echo %%i
set /a counter=!counter!+1
if !counter! gtr %1 exit /b
)
exit /b
Links:
SHIFT
…
Shifts the batch file arguments along, but does not affect %*. Thus, if %1=Hello 1, %2=Hello 2,
and %3=Hello 3, then, after SHIFT, %1=Hello 2, and %2=Hello 3, but %* is "Hello 1" "Hello 2" "Hello
3".
Links:
START
…
Starts a program in new window, or opens a document. Uses an unclear algorithm to determine
whether the first passed argument is a window title or a program to be executed; hypothesis: it
uses the presence of quotes around the first argument as a hint that it is a window title.
Examples:
start "notepad.exe"
Launches a new console window with notepad.exe being its title, apparently an undesired
outcome.
start
Starts a new console (command-line window) in the same current folder.
start .
Opens the current folder in Windows Explorer.
start ..
Opens the parent folder in Windows Explorer.
start /b TODO:example-application-where-this-is-useful
Starts the application without opening a new console window, redirecting the output to
the console from which the start command was called.
Links:
How to use command line switches to create a pre-addressed e-mail message in Outlook (http
s://support.microsoft.com/en-us/help/287573/how-to-use-command-line-switches-to-create-
a-pre-addressed-e-mail-message-in-outlook) , support.microsoft.com
TIME
…
Displays or sets the system time.
Links:
time at ss64.com (https://ss64.com/nt/time.html)
TITLE
…
Sets the title displayed in the console window.
Links:
TYPE
…
Prints the content of a file or files to the output.
Examples:
type filename.txt
type *.txt
Links:
VER
…
Shows the command processor or operating system version.
C:\>VER
...
Links:
mxpv/windows_build_numbers.txt (https://gist.github.com/mxpv/2935584#file-windows_buil
d_numbers-txt) , gist.github.com
VERIFY
…
Sets or clears the setting to verify whether COPY files etc. are written correctly.
Links:
VOL
…
Displays volume labels.
Links:
External commands
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.
ARP
…
Displays or changes items in the address resolution protocol cache, which maps IP addresses to
physical addresses.
Links:
AT
…
Schedules a program to be run at a certain time. See also SCHTASKS.
Links:
at at ss64.com (https://ss64.com/nt/at.html)
at at Microsoft (https://docs.microsoft.com/en-us/windows-server/administration/windows-c
ommands/at)
ATTRIB
…
Displays or sets file attributes. With no arguments, it displays the attributes of all files in the
current directory. With no attribute modification instructions, it displays the attributes of the files
and directories that match the given search wildcard specifications. Similar to chmod of other
operating systems.
Modification instructions:
Attributes:
A - Archived
H - Hidden
S - System
R - Read-only
Examples:
attrib
Displays the attributes of all files in the current directory.
attrib File.txt
Displays the attributes of the file.
attrib +r File.txt
Adds the "Read-only" attribute to the file.
attrib -a File.txt
Removes the "Archived" attribute from the file.
attrib -a +r File.txt
Removes the "Archived" attribute and adds the "Read-only" attribute to the file.
attrib +r *.txt
Acts on a set of files.
attrib /S +r *.txt
Acts recursively in subdirectories.
BCDEDIT
…
(Not in XP). Edits Boot Configuration Data (BCD) files. For more, type "bcdedit /?".
Links:
at Microsoft (https://docs.microsoft.com/en-us/windows-server/administration/windows-co
mmands/bcdedit)
CACLS
…
Shows or changes discretionary access control lists (DACLs). See also ICACLS. For more, type
"cacls /?".
Links:
CHCP
…
Displays or sets the active code page number. For more, type "chcp /?".
Links:
CHKDSK
…
Checks disks for disk problems, listing them and repairing them if wished. For more, type
"chkdsk /?".
Links:
CHKNTFS
…
Shows or sets whether system checking should be run when the computer is started. The
system checking is done using Autochk.exe. The "NTFS" part of the command name is
misleading, since the command works not only with NTFS file system but also with FAT and
FAT32 file systems. For more, type "chkntfs /?".
Links:
CHOICE
…
Lets the user choose one of multiple options by pressing a single key, and sets the error level as
per the chosen option. Absent in Windows 2000 and Windows XP, it was reintroduced in
Windows Vista, and has remained in Windows 7 and 8.
Examples:
Links:
CIPHER
…
Shows the encryption state, encrypts or decrypts folders on a NTFS volume.
Links:
CLIP
…
(Not in XP, or make a copy from Server 2003) Places the piped input to the clipboard.
Examples:
set | clip
Places the listing of environment variables to the clipboard.
Links:
CMD
…
Invokes another instance of Microsoft's CMD.
Links:
COMP
…
Compares files. See also FC.
Links:
COMPACT
…
Shows or changes the compression of files or folders on NTFS partitions.
Links:
CONVERT
…
Converts a volume from FAT16 or FAT32 file system to NTFS file system.
Links:
DEBUG
…
Allows to interactively examine file 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 file. Keywords: hex
dump, hexdump, hexadecimal dump, view hex, view hexadecimal, disassembler.
Debug offers its own command line. Once on its command like, type "?" to find about debug
commands.
To view hex of a file, invoke debug.exe with the file 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 file names. Use dir /x to find the 8.3 file name,
and apply debug on that one.
Links:
Debug (http://technet.microsoft.com/en-us/library/bb491040.aspx) at
technet.microsoft.com
W:Debug (command)
DISKCOMP
…
Compares the content of two floppies.
Links:
DISKCOPY
…
Copies the content of one floppy to another.
Links:
DISKPART
…
Shows and configures the properties of disk partitions.
Links:
DOSKEY
…
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.
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 first argument to notepad.
doskey /macrofile=doskeymacros.txt
Loads macro definitions from a file.
doskey /macros
Lists all defined macros with their definitions.
doskey /history
Lists the complete command history.
doskey /listsize=100
Sets the size of command history to 100.
Links:
Links:
EXPAND
…
Extracts files from compressed .cab cabinet files. See also #MAKECAB.
Links:
FC
…
Compares files, displaying the differences in their content in a peculiar way.
Examples:
Links:
fc at ss64.com (https://ss64.com/nt/fc.html)
fc at Microsoft (https://docs.microsoft.com/en-us/windows-server/administration/windows-c
ommands/fc)
FIND
…
Searches for a string in files or input, outputting matching lines. Unlike FINDSTR, it cannot
search folders recursively, cannot search for a regular expression, requires quotation marks
around the sought string, and treats space literally rather than as a logical or.
Examples:
find "(object" *.txt
Links:
FINDSTR
…
Searches for regular expressions or text strings in files. Does some of the job of "grep"
command known from other operating systems, but is much more limited in the regular
expressions it supports.
Treats space in a regular expression as a disjunction AKA logical or unless prevented with /c
option.
Examples:
And more.
Other limitations: There is a variety of limitations and strange behaviors as documented at What
are the undocumented features and limitations of the Windows FINDSTR command? (http://stac
koverflow.com/questions/8844868/what-are-the-undocumented-features-and-limitations-of-the-
windows-findstr-comman) .
Bugs:
Links:
FORFILES
…
Finds files by their modification date and file name pattern, and executes a command for each
found file. Is very limited, especially compared to the find command of other operating systems.
Available since Windows Vista. For more, type "forfiles /?".
Examples:
Links:
forfiles /?
FORMAT
…
Formats a disk to use Windows-supported file system such as FAT, FAT32 or NTFS, thereby
overwriting the previous content of the disk. To be used with great caution.
Links:
FSUTIL
…
A powerful tool performing actions related to FAT and NTFS file systems, to be ideally only used
by powerusers with an extensive knowledge of the operating systems.
Links:
GPRESULT
…
Displays group policy settings and more for a user or a computer.
Links:
Wikipedia:Group Policy
GRAFTABL
…
Enables the display of an extended character set in graphics mode. For more, type "graftabl /?".
Links:
HELP
…
Shows command help.
Examples:
help
Shows the list of Windows-supplied commands.
help copy
Shows the help for COPY command, also available by typing "copy /?".
Links:
ICACLS
…
(Not in XP) Shows or changes discretionary access control lists (DACLs) of files or folders. See
also CACLS. Fore more, type "icacls /?".
Links:
IPCONFIG
…
Displays Windows IP Configuration. Shows configuration by connection and the name of that
connection (i.e. Ethernet adapter Local Area Connection) Below that the specific info pertaining
to that connection is displayed such as DNS suffix and ip address and subnet mask.
Links:
LABEL
…
Adds, sets or removes a disk label.
Links:
MAKECAB
…
Places files into compressed .cab cabinet file. See also #EXPAND.
Links:
MODE
…
A multi-purpose command to display device status, configure ports and devices, and more.
Examples:
mode
Outputs status and configuration of all devices, such as com3 and con.
mode con
Outputs status and configuration of con device, the console in which the command
interpreter is running.
mode 120, 20
As above: Sets the number of columns (120) and lines (20), resulting in window resizing,
and clears the screen.
mode 120
As above: Sets the number of columns.
mode con cp
Outputs the current code page of the console.
Links:
MORE
…
Displays the contents of a file or files, one screen at a time. When redirected to a file, performs
some conversions, also depending on the used switches.
Examples:
more Test.txt
more *.txt
In some setups, seems to output gibberish if the input contains LF line breaks and tab
characters at the same time.
In some setups, for the conversion, /p may be unneeded. Thus, "more" would convert the
line breaks even without /p.
In some setups, tab conversion takes place automatically, even without the /t switch. If
so, it is per default to 8 spaces.
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.
Hypothesis: In Windows XP and Windows Vista, /e does not do anything; it is present for
compatibility reasons.
Links:
NET
…
Provides various network services, depending on the command used. Available variants per
command:
net accounts
net computer
net config
net continue
net file
net group
net help
net helpmsg
net localgroup
net name
net pause
net print
net send
net session
net share
net start
net statistics
net stop
net time
net use
net user
net view
Links:
OPENFILES
…
Performs actions pertaining to open files, especially those opened by other users over the
network. The actions involve querying, displaying, and disconnecting. For more, type "openfiles
/?".
Links:
openfiles at ss64.com (https://ss64.com/nt/openfiles.html)
PING
…
Syntax:
PING /?
PING address
PING hostname
Send ICMP/IP "echo" packets over the network to the designated address (or the first IP address
that the designated hostname maps to via name lookup) and print all responses received.
Examples:
ping en.wikibooks.org
ping 91.198.174.192
ping http://en.wikibooks.org/
Does not work.
Links:
RECOVER
…
Recovers as much information as it can from damaged files on a defective disk.
Links:
REG
…
Queries or modifies Windows registry.
The first argument is one of the following commands: query, add, delete, copy, save, load, unload,
restore, compare, export, import, and flags. To learn more about a command, follow it by /?, like
reg query /?.
Links:
REPLACE
…
Replaces files in the destination folder with same-named files in the source folder.
Links:
ROBOCOPY
…
(Not in XP) Copies files and folders. See also XCOPY and COPY.
Examples:
Links:
RUNDLL32
…
Runs a function available from a DLL. The available DLLs and their functions differ among
Windows versions.
Examples:
rundll32 sysdm.cpl,EditEnvironmentVariables
In some Windows versions, opens the dialog for editing environment variables.
Links:
at Microsoft (https://docs.microsoft.com/en-us/windows-server/administration/windows-co
mmands/rundll32)
SC
…
Controls Windows services, supporting starting, stopping, querying and more. Windows services
are process-like things. A Windows service is either hosted in its own process or it is hosted in
an instance of svchost.exe process, often with multiple services in the same instance. Processor
time use of a particular service can be found using freely downloadable Process Explorer from
Sysinternals, by going to properties of a service and then Threads tab. Another command
capable of controlling services is NET. TASKLIST can list hosted services using /svc switch.
Examples:
sc start wuauserv
Starts wuauserv service.
sc stop wuauserv
sc query wuauserv
sc query
Outputs information about all services.
Links:
sc at ss64.com (https://ss64.com/nt/sc.html)
Windows 7 Services at ss64.com (https://ss64.com/nt/syntax-services.html)
sc at Microsoft (https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/window
s-server-2012-R2-and-2012/cc754599%28v%3dws.11%29)
SCHTASKS
…
Schedules a program to be run at a certain time, more powerful than AT.
Links:
SETX
…
Like SET, but affecting the whole machine rather than the current console or process. Not
available in Windows XP; available in Windows Vista and later.
Links:
SHUTDOWN
…
Shuts down a computer, or logs off the current user.
Examples:
shutdown /s
Shuts down the computer.
shutdown /s /t 0
Shuts down the computer with zero delay.
shutdown /l
Logs off the current user.
Links:
SORT
…
Sorts alphabetically, from A to Z or Z to A, case insensitive. Cannot sort numerically: if the input
contains one integer per line, "12" comes before "9".
Examples:
sort File.txt
Outputs the sorted content of File.txt.
sort /r File.txt
Sorts in reverse order, Z to A.
dir /b | sort
Links:
SUBST
…
Assigns a drive letter to a local folder, displays current assignments, or removes an assignment.
Examples:
subst p: .
Assigns p: to the current folder.
subst
Shows all assignments previously made using subst.
subst /d p:
Removes p: assignment.
Links:
Links:
TASKKILL
…
Ends one or more tasks.
Examples:
Ends the process AKA task with process ID (PID) of 5792; the assumption is you have
found the PID using tasklist.
Links:
TASKLIST
…
Lists tasks, including task name and process id (PID).
Examples:
tasklist | sort
tasklist | find "AcroRd"
Links:
TIMEOUT
…
Waits a specified number of seconds, displaying the number of remaining seconds as time
passes, allowing the user to interrupt the waiting by pressing a key. Also known as delay or
sleep. Available in Windows Vista and later.
Examples:
timeout /t 5
Waits for five seconds, allowing the user to cancel the waiting by pressing a key.
timeout /t 5 /nobreak
Waits for five seconds, ignoring user input other than Control + C.
Links:
TREE
…
Displays a tree of all subdirectories of the current directory to any level of recursion or depth. If
used with /F switch, displays not only subdirectories but also files.
Examples:
tree
tree /f
Includes files in the listing, in addition to directories.
tree /f /a
As above, but uses 7-bit ASCII characters including "+", "-" and \" to draw the tree.
├───winevt
│ ├───Logs
│ └───TraceFormat
├───winrm
+---winevt
| +---Logs
| \---TraceFormat
+---winrm
Links:
tree at Microsoft (https://docs.microsoft.com/en-us/windows-server/administration/windows
-commands/tree)
WHERE
…
Outputs one or more locations of a file or a file name pattern, where the file or pattern does not
need to state the extension if it listed in PATHEXT, such as .exe. Searches in the current directory
and in the PATH by default. Does some of the job of "which" command of some other operating
systems, but is more flexible.
Available on Windows 2003, Windows Vista, Windows 7, and later; not available on Windows XP.
An alternative to be used with Windows XP is in the examples below.
Does not find internal commands, as there are no dot exe files for them to match.
Examples:
where find
Outputs the location of the find command, possibly "C:\Windows\System32\find.exe".
The .exe extension does not need to be specified as long as it is listed in PATHEXT, which
it is by default.
If there are more find commands in the path, outputs paths to both. In some situations, it
can output the following:
C:\Windows\System32\find.exe
C:\Program Files\GnuWin32\bin\find.exe
where /r . Tasks*
Searches for files whose name matches "Task*" recursively from the current folder.
Similar to "dir /b /s Tasks*". The /r switch disables search in the folders in PATH.
where *.bat
Outputs all .bat files in the current directory and in the directories that are in PATH. Thus,
outputs all .bat files that you can run without entering their full path.
where ls*.bat
As above, constraining also the beginning of the name of the .bat files.
where ls*
As above, but with no constraint on the extension. Finds lsdisks.bat, lsmice.pl, and
lsmnts.py if in the current directory or in the path.
where $path:*.bat
Outputs .bat files in the path but not those in the current folder unless the current folder is
in PATH. Instead of path, another environment variable containing a list of directories can
be used.
where $windir:*.exe
Outputs .exe files found in the folder stated in WINDIR environment variable.
Links:
WMIC
…
Starts Windows Management Instrumentation Command-line (WMIC), or with arguments given,
passes the arguments as commands to WMIC. Not in Windows XP Home. For more, type "wmic
/?".
Examples:
Links:
XCOPY
…
Copies files and directories in a more advanced way than COPY, deprecated in Windows Vista
and later in favor of ROBOCOPY. Type xcopy /? to learn more, including countless options.
Examples:
xcopy C:\Windows\system
Copies all files, but not files in nested folders, from the source folder
("C:\Windows\system") to the current folder.
Links:
External links