Windows Batch Scripting

This book describes the Microsoft-supplied command interpreter on Windows NT, Windows XP, Windows Vista, Windows 7 and later, which is cmd.exe.

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 cmd.exe 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".

Using the Windows command interpreter

How a command line is interpreted

The parsing of a command line into a sequence of commands is complex, and varies subtly from command interpreter to command interpreter. There are, however, four main components:

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. The name is ended by a second % character, except in special cases such as the batch file parameters %1, %2, and so forth.

Variable specifications are replaced with values. The value used to replace a variable specification is as follows:

Special names

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

Special variable names and what they expand to:

Name Replacement Value Used
%CD% The current directory, not ending in a slash character if it is not in the root directory of the current drive
%TIME% The system time in HH:MM:SS.mm format.
%DATE% The system date in a format specific to localization.
%RANDOM% A generated pseudo-random number between 0 and 32767.
%ERRORLEVEL% The error level returned by the last executed command, or by the last called batch script.
%CMDEXTVERSION% The version number of the Command Processor Extensions currently used by cmd.exe.
%CMDCMDLINE% The content of the command line used when the current cmd.exe was started.

Links:

Quoting and escaping

You can prevent the special characters that control command syntax from having their special meanings as follows, except for the percent sign (%):

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

Links:

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.

A compound command is a set of pipelines separated by conjunctions. The pipelines are executed sequentially, one after the other, and the conjunction controls whether the command interpreter executes the next pipeline or not. An example of a compound command (comprising two pipelines, which themselves are just simple commands) is move file.txt file.bak && dir > file.txt.

The conjunctions:

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:

Redirection

Redirection specifications are applied, and removed from the command line, before an individual command in a sequence is executed. Redirection specifications control where the standard input, standard output, and standard error file handles for a simple command point. They override any effects to those file handles that may have resulted from pipelining. (See the preceding section on command syntax.) Redirection signs > and >> can be prefixed with 1 for the standard output (same as no prefix) or 2 for the standard error.

The redirection specifications are:

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

How a command is executed

(...)

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 (
  echo A
  ping -n 2 127.0.0.1 >nul & REM wait
)

Ditto for any other enclosing, including this one:

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

To unset a variable, set it to empty string, such as "set myvar=".

The command interpreter inherits its initial set of environment variables from the process that created it. In the case of command interpreters invoked from desktop shortcuts this will be Windows Explorer, for example.

Command interpreters generally have textual user interfaces, not graphical ones, and so do not recognize the 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.

An example content of PATHEXT printed by "echo %PATHEXT%":

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

Adding ".PL" to the variable in Windows Vista and later:

Links:

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
$A & symbol AKA ampersand. A convenience, since it is difficult to place a literal & in 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 '<'
$M Remote name linked to the current drive if it is a network drive; empty string 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
$* All arguments thereafter. Something like it. Someone fix this comment.

Links:

Switches

Most Windows commands provide switches AKA options to direct their behavior.

Observations:

Examples:

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:

Uses of the error level:

Examples:

Links:

String processing

Getting a substring of a variable by position and length:

Before running the following examples, ensure that %a% equals "abcd" by running this:

The examples:

Testing substring containment:

Testing for "starts with":

String replacement:

See also the help for SET command: set /?.

Splitting a string by any of " ", ",", and ";": ["space", "comma" and "semicolon":]

set myvar=a b,c;d
for %%a in (%myvar%) do echo %%a

Splitting a string by semicolon, assuming the string contains no quotation marks:

@echo 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

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:

if not -%1-==-- echo Argument one provided
if -%1-==-- echo Argument one not provided & exit /b

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

Transferring command-line arguments to environment variables:

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

Looping over all command-line arguments, albeit not a robust one:

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

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

Finding the number of command-line arguments, in a non-robust way:

set argcount=0
for %%i in (%*) do set /a argcount+=1

Again, this does not work with arguments containing wildcards.

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:

Thus, the following lines pass the same four arguments:

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:

Links:

Wildcards

Many commands accept file name wildcards--characters that do not stand for themselves and enable matching of a group of filenames.

Wildcards:

Examples:

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:

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\
%~n1 For a file, the file name without path and extension

For a folder, the folder name

notepad
%~x1 File name extension including the period .exe
%~s1 Modify of f, n and x to use short name Not provided
%~a1 File attributes --a------
%~t1 Date and time of last modification of the file 02.11.2006 11:45
%~z1 File size 151040
%~pn1 A combination of p and n \Windows\System32\notepad
%~dpnx1 A combination of several letters C:\Windows\System32\notepad.exe
%~$PATH:1 The full path of the first match found in the folders present in the PATH variable, or an empty string in no match.
%~n0 %~n applied to %0:

The extensionless name of the batch

tildetest
%~nx0 %~nx applied to %0:

The name of the batch

tildetest.bat
%~d0 %~f applied to %0:

The drive letter of the batch

C:
%~dp0 %~dp applied to %0:

The folder of the batch with trailing backslash

C:\Users\Joe Hoe\
%* all args in prompt or whatever

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.

An example of a function that determines arithmetic power:

@echo off
call :power 2 4
echo %result%
rem Prints 16, determined as 2 * 2 * 2 * 2
goto :eof

rem __Function power______________________
rem Arguments: %1 and %2
:power
setlocal
set counter=%2
set interim_product=%1
:power_loop
if %counter% gtr 1 (
  set /a interim_product=interim_product * %1
  set /a counter=counter - 1
  goto :power_loop
)
endlocal & set result=%interim_product%
goto :eof

While the goto :eof at the end of the function is not 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:

(See Command-line arguments as a reminder)

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.

Arithmetic operators include *, /, % (modulo), +, -. In a batch, modulo has to be entered as "%%".

Bitwise operators interpret the number as a sequence of 32 binary digits. These are ~ (complement), & (and), | (or), ^ (xor), << (left shift), >> (right shift).

A logical operator of negation is !: it turns zero into one and non-zero into zero.

A combination operator is ,: it allows more calculations in one set command.

Combined assignment operators are modeled on "+=", which, in "a+=b", means "a=a+b". Thus, "a-=b" means "a=a-b". Similarly for *=, /=, %=, &=, ^=, |=, <<=, and >>=.

The precedence order of supported operators, is as follows:

  1. ( )
  2. * / % + -
  3. << >>
  4. &
  5. ^
  6. |
  7. = *= /= %= += -= &= ^= |= <<= >>=
  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:

Examples:

An example calculation that prints prime numbers:

@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:

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:

The above are also known as command prompt keyboard shortcuts.

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:

Links:

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!
)

:: For each item in the array, not knowing the length
set i=1
:startloop
if not defined array_%i% goto endloop
set array_%i%=!array_%i%!_dummy_suffix
echo A%i%: !array_%i%!
set /a i+=1
goto startloop
:endloop

Links:

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:

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:

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:

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

Links:

BREAK

In Windows versions based on Windows NT, does nothing; kept for compatibility with MS DOS.

Links:

CALL

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

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:

Links:

CHDIR

A synonym of CD.

CLS

Clears the screen.

COLOR

Sets the console foreground and background colors.

Examples:

Links:

COPY

Copies files. See also MOVE.

Examples:

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:

Links:

DIR

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

Examples:

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.

Links:

ECHO

Displays messages, or turns command echoing on or off.

Examples:

Displaying a string without a newline requires a trick:

Links:

ELSE

An example:

if exist file.txt (
  echo The file exists.
) else (
  echo The file does not exist.
)

See also IF.

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:

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.

Examples:

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:

Links:

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.

Available elementary tests:

To each elementary test, "not" can be applied. Apparently there are no operators like AND, OR, etc. to combine elementary tests.

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

An example:

if not exist %targetpath% (
  echo Target path not found.
  exit /b
)

Examples:

Links:

MD

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

Examples:

Links:

MKDIR

A synonym for MD.

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:

Links:

PATH

Outputs or sets the value of the PATH environment variable. When outputing, includes "PATH=" at the beginning of the output.

Examples:

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:

Links:

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 A remark that does not get executed
echo Hello REM This remark gets displayed by echo
echo Hello & REM This remark gets ignored as wished
:: This sentence has been marked as a remark using double colon.

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.

An alternative to REM is double 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:

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.

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 after the execution reaches the location of their use rather than at an earlier point.

The following is an example of using delayed expansion in a script that prints the specified number of first lines of a file, providing some of the function of the command "head" known from other operating systems:

@echo off

call :myhead 2 File.txt
exit /b

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

Links:

TIME

Displays or sets the system time.

Links:

TITLE

Sets the title displayed in the console window.

Links:

TYPE

Prints the content of a file or files to the output.

Examples:

Links:

VER

Shows the command processor or operating system version.

C:\>VER

Microsoft Windows XP [Version 5.1.2600]

C:\>

Some version strings:

The word "version" appears localized.

Links:

VERIFY

Sets or clears the setting to verify whether COPY files etc. are written correctly.

Links:

VOL

Displays volume labels.

Links:

External commands

External commands available to Windows command interpreter are separate executable program files, supplied with the operating system by Microsoft, or bundled as standard with the third-party command interpreters. By replacing the program files, 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.

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:

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:

Examples:

For more, type "attrib /?".

Links:

BCDEDIT

(Not in XP). Edits Boot Configuration Data (BCD) files. For more, type "bcdedit /?".

Links:

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:

An alternative is "set /p"; see SET.

Links:

CIPHER

Shows the encryption state, encrypts or decrypts folders on a NTFS volume.

Links:

CLIP

(Not in XP) Places the piped input to the clipboard.

Examples:

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:

Links:

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:

Command history-related examples:

To get help on doskey from command line, type "doskey /?".

Links:

DRIVERQUERY

Shows all installed device drivers and their properties.

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:

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:

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:

Limitations of the regular expressions of "findstr", as compared to "grep":

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

Bugs:

Also consider typing "findstr /?".

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:

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:

GRAFTABL

Enables the display of an extended character set in graphics mode. Fore more, type "graftabl /?".

Links:

HELP

Shows command help.

Examples:

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:

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:

Switch /e:

Links:

NET

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

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:

PING

Syntax:

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.

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.

Links:

RUNDLL32

Runs a function available from a DLL. The available DLLs and their functions differ among Windows versions.

Examples:

Links:

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.

Links:

SORT

Sorts alphabetically, from A to Z or Z to A. Cannot sort numerically: if the input contains one integer per line, "12" comes before "9".

Examples:

Links:

SUBST

Assigns a drive letter to a local folder, displays current assignments, or removes an assignment.

Examples:

Links:

SYSTEMINFO

Shows configuration of a computer and its operating system.

Links:

TASKKILL

Ends one or more tasks.

Examples:

Links:

TASKLIST

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

Examples:

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:

Workaround in Windows XP:

Perl-based workaround in Windows XP, requiring Perl installed:

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:

A snippet of a tree using 8-bit ASCII characters:

├───winevt
│   ├───Logs
│   └───TraceFormat
├───winrm

A snippet of a tree using 7-bit ASCII characters:

+---winevt
|   +---Logs
|   \---TraceFormat
+---winrm

Links:

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:

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. Type xcopy /? to learn more, including countless options.

Examples:

Links:

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.