Windows Batch Scripting
This book aims to introduce users of Microsoft Windows to the Microsoft-supplied command interpreter on Windows NT, which is cmd.exe. It does not cover other command interpreters available, such as 4NT from JP Software and CMD from the ReactOS project. 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.
C:\>VER Microsoft Windows XP [Version 5.1.2600] C:\>
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 find a list of all MS-DOS commands and a definition for all of them, open the command prompt on all Microsoft/Windows computers, 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.
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 devolved 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:
- For variable specification names that match the names of environment variables, the replacement is the value of the named environment variable. For example: %PATH% is replaced by the value of the PATH environment variable.
- For variable specifications that name batch file parameters (i.e. that are non-negative decimal numbers), the replacement is the value of the parameter taken from the arguments with which the batch file 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.
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
To prevent the metacharacters that control command syntax and redirection from having their special meanings, quoting is used. This takes two forms:
- Although they don't process quotation marks, in command arguments, specially themselves, but simply pass them along as-is to the commands executed, command interpreters do recognise when quotation marks (") surround metacharacters. The & metacharacter does not have its usual effect on command syntax if it is within a pair of quotation marks.
- e.g. The command line echo "&" will invoke the ECHO command passing it the three characters "&" as its command tail, rather than split the command line in twain at the & character as would occur if the character were not within quotation marks.
- The "escape" character (always a ^ in Microsoft's CMD) used in front of a metacharacter also prevents that metacharacter from having its usual effect on command syntax. The "escape" character itself is stripped from the command line before it is passed to the command actually being invoked.
- e.g. The command line echo ^& will invoke the ECHO command passing it the character & as its command tail, rather than split the command line in twain at the & character as would otherwise occur.
Syntax
Command lines are devolved 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 are:
- &
- The simplest 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.
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:
- dir *.txt >listing.log
- Redirects the output of the dir command to listing.log file.
- dir *.txt 2>NUL
- Redirects errors of the dir command to nowhere.
- dir *.txt >listing.log 2>&1
- Redirects the output of the dir command to listing.log file, along with the error messages.
- dir *.txt >listing.log 2>listing-errors.log
Links:
How a command is executed
(...)
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.
PROMPT
The value of the PROMPT environment variable controls the text that is emitted whenever the command interpreter displays the prompt (i.e. whenever prompting for a new command line in interactive mode, or whenever 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 | Effect |
|---|---|
| $$ | Causes the $ character itself to be written out |
| $A | Causes a & symbol to be written out (This is a convenience measure, since it is difficult, because it involves quoting, to place a literal & in the value of the PROMPT environment variable using the SET command.) |
| $B | ' (pipe symbol) to be written out |
| $C | Left parenthesis '(' |
| $D | Prints current date |
| $E | ESC (ASCII code 27) |
| $F | Right parenthesis ')' |
| $G | Prints greater-than symbol '>' |
| $H | Backspace (deletes previous character) |
| $L | Prints less-than symbol '<' |
| $N | Prints current drive letter |
| $P | Prints current drive letter and full path |
| $Q | Prints '=' (equals sign) |
| $S | Prints ' ' (space character) |
| $T | Prints current system time |
| $V | Prints Windows XP version number |
| $_ | Prints <CR> (carriage return character, aka "enter") |
This table is incomplete. You can help Wikibooks by expanding it.
String processing
Getting a substring of a variable by position and length:
Before running the following examples, ensure that %a% equals "abcd" by running this:
- set a=abcd
The examples:
- echo %a:~0,1%
- Result: a
- echo %a:~1,1%
- Result: b
- echo %a:~0,2%
- Result: ab
- echo %a:~1,2%
- Result: bc
- echo %a:~1%
- Result: bcd
- echo %a:~-1%
- Result: d
- echo %a:~-2%
- Result: cd
- echo %a:~0,-2%
- Result: ab
- echo %a:~0,-1%
- Result: abc
- echo %a:~1,-1%
- Result: bc
Testing substring containment:
- if not "%a:bc=%"=="%a%" echo yes
- If variable a contains "bc" as a substring, echo "yes".
- This test is a trick that uses string replacement, discussed below.
- This test does not work if the variable contains a quotation mark.
Testing for "starts with":
- if %a:~0,1%==a echo yes
- If variable a starts with "a", echo "yes".
- if %a:~0,2%==ab echo yes
- If variable a starts with "ab", echo "yes".
String replacement:
- set a=abcd & echo %a:c=%
- Result: abd
- set a=abcd & echo %a:c=e%
- Result: abed
- set a=abcd & echo %a:*c=%
- Result: d
- The asterisk only works at the beginning of the sought pattern; it does not work at the end or in the middle.
See also the help for SET command: set /?.
Splitting a string by any of " ", ",", and ";":
- set myvar=a b,c;d
- for %a in (%myvar%) do echo %a
Splitting a string by semicolon, assuming the string contains no quotation marks:
@echo 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.
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
Looping over all command-line arguments (for each command-line argument, ...):
- for %%i in (%*) do (
- echo %%i
- )
Finding the number of command-line arguments:
- set argnumber=0
- for %%i in (%*) do set /a argnumber+=1
See also SHIFT.
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.
When passing arguments to a batch script, characters used for argument separation include a space, comma, and semicolon. Thus, the following lines pass the same four arguments:
- test.bat a b c d
- test.bat a,b,c,d
- test.bat a, b, c, d
- test.bat a;b;c;d
- test.bat a b,c;,;d
Yes, even the line with "a b,c;,;d" passes four arguments.
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.
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 default 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. |
| 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 poped 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.
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:
- cd
- cd C:\Program Files
- cd \Program Files
- cd Documents
- cd %USERPROFILE%
No surrounding quotes are needed around paths with spaces.
Links:
CHDIR
A synonym of #CD.
CLS
Clears the screen.
COPY
Copies files. See also MOVE.
Examples:
- copy F:\File.txt
- Copies the file into the current directory, assuming the current directory is not F:\.
- copy "F:\My File.txt"
- As above; quotation marks are needed to surround a file with spaces.
- 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.
- copy File1.txt File2.txt
- Copies File1.txt to File2.txt, overwriting File2.txt if confirmed by the user or if run from a batch script.
- copy File.txt "My Directory"
- Copies File.txt into "My Directory" directory, assuming "My Directory" exists.
- copy Dir1 Dir2
- Copies all files directly located in directory Dir1 into Dir2, assuming Dir1 and Dir2 are directories. Does not copy files located in nested directories of Dir1.
Links:
DEL
Deletes files. Use with caution, especially in combination with wildcards.
Links:
DIR
Lists the contents of a directory. Offers a range of options.
Examples:
- 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
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
Links:
- date at ss64.com
- How to get current datetime on Windows command line, in a suitable format for using in a filename? 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 ECHO Owner ^& son
- echo 1&echo 2&echo 3
- Displays three strings, each followed by a newline.
Displaying a string without a newline requires a trick:
- set <NUL /p=Output of a command:
- Displays "Output of a command:". The output of the next command will be displayed immediately after ":".
- set <NUL /p=Current time: & time /t
- Displays "Current time: " followed by the output of "time /t".
- (set <NUL /p=Current time: & time /t) >tmp.txt
- Like before, with redirecting the output of both commands to a file.
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:
- 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.
Examples:
- for %i in (1,2,3) do echo %i
- From a command line, echo 1, 2, and 3.
- for %%i in (1,2,3) do echo %%i
- In a batch, echo 1, 2, and 3.
- for %i in (1 2,3;4) do echo %i
- Echo 1, 2, 3, and 4. Yes, a mixture of item separators is used.
- for /L %i in (1,1,10) do echo %i
- Echo the numbers from 1 to 10.
- for /f "tokens=*" %i in (list.txt) do echo %i
- For each line in a file, echo the line.
- for /f "tokens=1-3 delims=:" %a in ("First:Second:Third") do echo %c-%b-%a
- Parse a string into tokens delimited by ":". Note how the second and third tokens are stored in %b and %c even though %b and %c are not expressly mentioned in the part of the command before "do".
- for /f "tokens=*" %i in ('cd') do echo %i
- For each line of the result of a command, echo the line.
Links:
FTYPE
Displays or sets the command to be executed for a file type.
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.
Links:
IF
Conditionally executes a command.
Documentation is available by entering IF /? to CMD prompt.
What is not documented is that the IF command barfs when it encounters a string containing a '/' character. This can be very frustrating when you need to process a line with this fairly common character that should never be excluded. The problem no doubt comes from the IF command confusing the '/' as part of a /I (or /?) directive on the IF command line.
Available elementary tests:
- exist <filename>
- <string>==<string>
- <expression1> equ <expression2> -- equals
- <expression1> neq <expression2> -- not equal
- <expression1> lss <expression2> -- less than
- <expression1> leq <expression2> -- less than or equal
- <expression1> gtr <expression2> -- greater then
- <expression1> geq <expression2> -- greater than or equal
- defined <variable>
- errorlevel <number>
- cmdextversion <number>
To each elementary test, "not" can be applied.
The /I switch makes the == and equ comparisons ignore case.
An example:
if not exist %targetpath% ( echo Target path not found. exit /b )
Links:
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 "My Dir With Spaces"
- Creates a directory with a name containing spaces in the current directory.
Links:
MKDIR
A synonym for MD.
MOVE
Moves files or directories between directories, or renames them. See also REN.
Examples:
- move File1.txt File2.txt
- Renames File1.txt to File2.txt, overwriting File2.txt if confirmed by the user or if run from a batch script.
- move File.txt Dir
- Moves File.txt file into Dir directory, assuming File.txt is a file and Dir is a directory; overwrites target file Dir\a.txt if conditions for overwriting are met.
- move Dir1 Dir2
- Renames directory Dir1 to Dir2, assuming Dir1 is a directory and Dir2 does not exist.
- move Dir1 Dir2
- Moves directory Dir1 into Dir2, resulting in existence of Dir2\Dir1, assuming both Dir1 and Dir2 are existing directories.
- move F:\File.txt
- Moves the 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
Displays or sets the value of the PATH environment variable.
PAUSE
Prompts the user and waits for a line of input to be entered.
POPD
Changes to the drive and directory poped 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.
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.
Examples:
- rd Dir1
- rd Dir1 Dir2
- rd "My Dir With Spaces"
REN
Renames files and directories.
Examples:
- ren filewithtpyo.txt filewithtypo.txt
- ren *.cxx *.cpp
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:
- 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 HOME=%HOME%;C:\Program Files\My Bin Folder
- set /P user_input=Enter an integer:
- set /A result = 4 * ( 6 / 3 )
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. Thus, if %1=Hello 1, %2=Hello 2, and %3=Hello 3, then, after SHIFT, %1=Hello 2, and %2=Hello 3.
Links:
START
Starts in new window.
START /LOW program.exe ECHO started and not waiting for finish
This example starts program.exe with a low priority and then immediately follows next command.
TIME
Displays or sets the system time.
Links:
TYPE
Prints the content of a file or files to the output.
Examples:
- type filename.txt
- type a.txt b.txt
- type *.txt
- type NUL > tmp.txt
- Create an empty file (blank file).
Links:
VER
Shows the command processor or operating system version.
VERIFY
Sets or clears the setting to verify whether COPY files etc. are written correctly.
VOL
Displays volume labels.
External commands
External commands available to Windows command interpreted 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.
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:
- To add an attribute, attach a '+' in front of its letter.
- To remove an attribute, attach a '-' in front of its letter
- Attributes:
- A - Archived
- H - Hidden
- S - System
- R - Read-only
- ...and possibly others.
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.
For more, type "attrib /?".
Links:
CMD
Synopsys
- CMD /?
- CMD
- CMD /C command
Description
Invoke another instance of Microsoft's CMD.
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 /macros | find "da"
- Lists all macro definitions that contain "da" as a substring; see also FIND.
Command history-related examples:
- doskey /history
- Lists the complete command history.
- doskey /history | find "dir"
- Lists each line of command history that contains "dir" as a substring
- doskey /listsize=100
- Sets the size of command history to 100.
To get help on doskey from command line, type "doskey /?".
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:
- find "(object" *.txt
- dir /S /B | find "receipt"
- dir /S /B | find /I /V "receipt"
- Prints all non-matching lines in the output of the dir command, ignoring letter case.
- find /C "inlined" *.h
- Instead of outputting the matching lines, outputs their count. If more than one file is searched, outputs one count number per file preceded with a series of dashes followed by the file name; does not output the total number of matching lines in all files.
- find /C /V "" < file.txt
- Outputs the number of lines AKA line count in "file.txt". Does the job of "wc -l" of other operating systems. Works by treating "" as a string not found on the lines. The use of redirection prevents the file name from being output before the number of lines.
- type file.txt | find /C /V ""
- Like the above, with a different syntax.
- type *.txt 2>NUL | find /C /V ""
- Outputs the sum of line counts of the files ending in ".txt" in the current folder. The "2>NUL" is a redirection of standard error that removes the names of files followed by empty lines from the output.
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:
- findstr /s "[0-9][0-9].*[0-9][0-9]" *.h *.cpp
- Searches recursively all files whose name ends with dot h or dot cpp, priting only lines that contain two consecutive decimal digits followed by anything followed by two consecutive decimal digits.
- findstr "a.*b a.*c" File.txt
- Outputs all lines in File.txt that match any of the two regular expressions separated by the space. Thus, the effect is one of logical or on regular expressions.
- findstr /r /c:"ID: *[0-9]*" File.txt
- Outputs all lines in File.txt that match the single regular expression containing a space. The use of /c prevents the space from being treated as a logical or. The use of /r switches the regular expression treatment on, which was disabled by default by the use of /c. To test this, try the following:
- echo ID: 12|findstr /r /c:"ID: *[0-9]*$"
- Matches.
- echo ID: 12|findstr /c:"ID: *[0-9]*$"
- Does not match, as the search string is not interpreted as a regular expression.
- echo ID: abc|findstr "ID: *[0-9]*$"
- Matches despite the output of echo failing to match the complete regular expression: the search is interpreted as one for lines matching "ID:" or "*[0-9]*$".
- echo ID: 12|findstr /r /c:"ID: *[0-9]*$"
- Outputs all lines in File.txt that match the single regular expression containing a space. The use of /c prevents the space from being treated as a logical or. The use of /r switches the regular expression treatment on, which was disabled by default by the use of /c. To test this, try the following:
- findstr /ric:"id: *[0-9]*" File.txt
- Does the same as the previous example, but in a case-insensitive manner.
- While findstr enables this sort of accumulation of switches behind a single "/", this is not possible with any command. For instance, "dir /bs" does not work, while "dir /b /s" does.
- To test this, try the following:
- echo ID: 12|findstr /ric:"id: *[0-9]*$"
- echo ID: ab|findstr /ric:"id: *[0-9]*$"
Limitations of the regular expressions of "findstr", as compared to "grep":
- No support of groups -- "\(", "\)".
- No support of greedy iterators -- "*?".
- No support of "zero or one of the previous" -- "?".
- 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?.
Also consider typing "findstr /?".
Links:
- findstr at ss64.com
- findstr at Microsoft
- What are the undocumented features and limitations of the Windows FINDSTR command? at StackOverflow
IPCONFIG
Synopsys
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.
- IPCONFIG /?
- IPCONFIG
(...)
Description
(...)
Links:
MORE
Synopsys:
- MORE /?
- MORE [/E]
- MORE [/E] filename
Displays the contents of a file or files, one screen at a time.
Links:
NET
Synopsys
- NET /?
- 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:
PING
Synopsys
- PING /?
- PING address
- PING hostname
Description
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:
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:
- 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 or displays current assignments.
Links:
TASKKILL
Ends one or more tasks.
Examples:
- taskkill /IM AcroRd32.exe
- Ends all process with the name "AcroRd32.exe"; thus, ends all open instances of Acrobat Reader. The name can be found using tasklist.
- tasklist | find "notepad"
taskkill /PID 5792
- 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"
- tasklist | find /C "chrome.exe"
- Displays the number of tasks named "chrome.exe", belonging to Google Chrome browser.
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.
Links:
WHERE
Displays the location of a file, searching in the current directory and in the PATH by default. Does some of the job of "which" command of some other operating systems.
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".
- for %i in (find.exe) do @echo %~$PATH:i
- Outputs the location of "find.exe" on Windows XP. The name has to include ".exe", unlike with the where command.
- where /r . Tasks*
- Searches for files whose name matches "Task*" recursively from the current folder. Similar to "dir /b /s Tasks*"
Links:
XCOPY
Copies files and directories in a more advanced way than COPY, deprecated in Windows Vista and later.
Links:
External links
- Windows XP - Command-line reference A-Z at microsoft.com
- Windows CMD Commands at ss64.com -- licensed under Creative Commons Attribution-Non-Commercial-Share Alike 2.0 UK: England & Wales[1], and thus incompatible with CC-BY-SA used by Wikibooks
- The FreeDOS HTML Help at fdos.org -- a hypertext help system for FreeDOS commands, written in 2003/2004, available under the GNU Free Documentation License