Windows 7 / Getting Started

Built-in Commands

CMD recognizes and interprets several commands directly. Many of these commands are helpful when writing batch files. In this section, Reference List below lists the built-in commands.

Many commands have features called command extensions. Command extensions are enabled by default in Windows 7,Vista, and XP, but they can be disabled if necessary.

REFERENCE LIST 10.1 CMD's Built-in Commands :label

Defines the target for a goto or call statement. Useful only in batch files.

@command

Executes command without echoing it to the console, if echoing is enabled.This is mostly used at the beginning of batch files to disable all command echoing: @echo off.

a:
b:
c:
etc

A command consisting solely of a letter and a colon changes the default or "current" drive to the indicated disk drive. Use the cd or pushd command to change the default or "current" directory.

assoc [.extension[=[filetype]]]

The assoc command displays or sets associations between file extensions such as .DOC and file types such as "Word.Document.12." (This is the information behind the associations that Explorer displays and edits in its Tools, Folder Options, File Types dialog box.) The assoc command can take several forms:

Command 	Result
assoc 		Lists all associations.
assoc 		.xxx Lists the association for extension .xxx.
assoc 		.xxx= Deletes the association for .xxx.
assoc 		.xxx=type Sets the association for .xxx to type. Type
		must be a file type listed in the Registry under
		HKEY_CLASSES_ROOT.

The assoc command isn't too useful, but it can help you to quickly find the application associated with a given file extension. Use assoc to list the file type for the extension, and then use the ftype command to find the linked application.

break

This command does nothing. Under MS-DOS, it is used to enable and disable Ctrl+C checking.

call batchfile [arguments...]
call :label [arguments...]

Performs a "subroutine" call. Executes a secondary batch file or transfers control to a specified label within the current batch file. Control returns to the statement after the call when the subroutine reaches the end of file or an exit /B statement.

cd [/d] [[drive:]directory]

Changes the current working directory to the specified path, which might be a relative or absolute path. If a drive letter is specified, the default directory for that drive is changed, but the working drive (the Command Prompt window's default drive) is not changed unless you add the /d option.With no arguments, cd prints the current directory.

As a convenience, you do not need to use quotes, even if the directory name contains spaces. For example,

cd \Program Files

works correctly.You can also use name completion to help fill in long pathnames if you are typing cd commands on the command line. For example, cd \Pr followed by the Tab key should complete the path "\Program Files" with Windows automatically adding the quotes.

chdir

Chdir is identical to the cd command and takes the same arguments.

cls

Clears the screen (the Command Prompt window).

color [bf]

Allows you to change the background and text colors of the current Command Prompt window.The argument to color is a two-letter code.The first letter is the code for the screen background color, taken from the values listed in Table below. The second letter is the code for the text color. For example, the command color 1e requests yellow text on a dark blue background.With no arguments, color restores the screen's colors to their initial settings.

You can also set a Command Prompt window's colors using its Properties dialog box.

copy [/d] [/v] [/n] [/l] [/y|/-y] [/z] [/a|/b]
     source [/a|/b] [+source [/a|/b]]... [destination [/a|/b]]

The copy command copies files from one location to another and can also make a copy of a file in the same directory but with a different name.The simplest version of the command just lists the name of the original (source) file and the name to give the copy:

copy mydata.dat e:\files\april2002data.dat
copy mydata.dat mydata.backup

The destination name can be a full filename, or if the copy is to have the same name as the original, just a folder pathname.

Wildcards can be used in the source filename to copy multiple files. If this is the case, the destination name must be a folder name.

If you list multiple source files on the command line separated by + signs, they are combined (concatenated) into one destination file. If you want to copy multiple files separately and can't write their names using a wildcard format, you need to issue multiple copy commands.

Other options might be specified on the command line, as listed here:

OptionResult
/aCopies the file in ASCII (text) mode. A Ctrl+Z character in the file is taken to mean "end of file" and no more data is read.
/bCopies the file in binary (data) mode. (I have never needed the /a and /b options, but should you find them necessary, you can specify one or the other at the beginning of the copy command to apply to all files, or you can add them after individual file names.)
/dThe destination file will be unencrypted, even if the original file is encrypted.
lIf the named file is a symbolic link, the link is copied, not the file to which the link refers.
/nGives the destination copy a short "8.3" filename.
/vWindows should read the copied file back and compare it to the original to be sure that the copy is correct.This option is especially useful when copying to floppy, Zip, or other removable disks.
/yLets copy overwrite any existing files without asking for confirmation.
/-yMakes copy always ask for confirmation before overwriting an existing file.
/-zLets copying resume after a temporary network disconnection and displays a percentage-complete indicator while copying. Used for copying across a network.

The /y argument makes copy silently overwrite any existing files of the same name as the destination file. If /-y is specified, copy always prompts before overwriting.

The default behavior is to prompt if copy is entered from the command line, and not to prompt if copy is used in a batch file.You can change these defaults by assigning the value /y or /-y to the COPYCMD environment variable. In any case, if you specify /y or /-y on the command line, this overrides the default setting. Any other copy options might be included in the COPYCMD environment variable to set the command's default behavior.The COPYCMD environment variable also affects the move command.

date [/t | newdate]

With no arguments, date displays the current date and requests that you type in a new date.You can press Enter to keep the current date.You can also set the date by specifying the new date on the command line.The date must be formatted according to the localized date format. For example, in the United States, the format is mm-dd-yyyy or mm/dd/yyyy also see the time command).With /t on the command line, date displays the date without prompting for a replacement. (This is useful if you want to just print the date in the text output of a batch file, for example.)

del [/p] [/f] [/s] [/q] [/a[[:]attributes]] filename ...

Deletes files named on the command line. One or more filenames might be named, and wildcards might be used.The filenames can include a path. If no path is specified, they are deleted from the current directory.

Caution Files deleted by del are removed immediately and permanently. They do not go to the Recycle Bin.

If a directory name is listed by itself, all the files in the directory are deleted, although the directory itself is not removed (for that, use the rd command). For example, the following two commands have the same effect:

del c:\temp\*.*
del c:\temp

Here are the command-line options:

Option 		Effect
/p 		Prompts to confirm deleting each file.
/f 		Forces deletion of read-only files.
/s 		Recurses subdirectories of the current or
		named directories, deleting any files with the
                specified name(s).
/q 		Quiet mode. Does not ask for confirmation if you
		enter *.* as the filename.
/a 		Selects files to delete based on specified
                file attributes. After /a and an optional colon,
                enter one or more of the following attribute codes:
		r-Read-only files
		s-System files
		h-Hidden files
		a-Files with the archive bit set
		i-Files marked not to be indexed
		l-Reparse points and symbolic links
		--Before an attribute code, means not
		You can specify more than one attribute. 
                For example, /a:hr
		indicates that only files that are both hidden
                and read-only are to be deleted.

Here are some examples of del commands:

  • del myfile.doc
    Deletes myfile.doc from the current directory
  • del /q c:\temp\*.*
    Deletes all files in C:\temp without prompting
  • del /s c:\temp\*.tmp
    Deletes .TMP files from C:\temp and all subfolders
  • del /a:h *.*
    Deletes all files from the current directory, even hidden files
dir pathname ... [/p] [/q] [/r] [/w|/d|/b|/n|/x] [/s] [/l] [/c] [/4]
[/a[ [:]attributes]] [/o [[:]sortfields]] [/t[[:]timefield]]

The dir command lists the names of files and/or subfolders found in specified folders.With no arguments, the dir command lists all the files and folders in the current directory.The basic directory listing includes a title, a list of files with their sizes and last-modified dates, and a total count of files and bytes used. I discuss the dir command in more detail after this reference listing.

echo on|off
echo text
echo.

The first version enables or disables echoing of batch file commands to the console during execution.The second version writes the specified text to the standard output, which either appears in the console window or is written to another file or program, if the standard output is redirected.The third version prints a completely blank line-that is, just a carriage return and line feed. Echo, by itself, prints its on/off status.

endlocal

(See setlocal.)

erase

Erase is identical to the del command and takes the same arguments.

exit [/b] [exitcode]

Terminates the current Command Prompt console window or batch file. In a batch file, exit /b terminates the batch file (or the batch file subroutine) without terminating CMD as well.The optional numeric exitcode argument specifies an exit code.With /b, this command sets the ERRORLEVEL environment variable to the specified value; otherwise, it sets CMD's exit code.

for [modifiers] %variable in (set) do command [arguments]

or, in batch files,

for [modifiers] %%variable in (set) do command [arguments]

Executes command repeatedly, with variable taking on one of the values from a specified set of values at each iteration.The variable name is a single letter and is casesensitive. In the usual usage, set is a list of strings or filenames (possibly specified with wildcards).

If the for command is used in a batch file, the percent signs must be doubled up to prevent them from being interpreted as argument or environment variable substitutions.

If an environment variable is used on the command line and its value changes as the for command proceeds, the results might not be what you expect.

The for command is discussed in more detail after the reference list.

ftype [.extension[=[filetype]]]

The ftype command is a partner to the assoc command and displays or sets the associations between file types such as "Word.Document.8" and the commands used to open the files for editing.The ftype command can take several forms:

Command 	Result
ftype 		Lists all associations
ftype 		FileType Lists the association for the named FileType
ftype 		FileType= Deletes an association
ftype 		FileType=command Sets the open command for the named
                FileType to command

In the command string, symbols of the form %1 and %* indicate how any other arguments from the original command line are to be passed to the open command. To get more information on the argument format for ftype commands, open a Command Prompt window and type ftype /?.

The ftype command isn't all that useful, but it can help you to find the application associated with a given file extension. Use the assoc command to list the file type for the extension, and then use ftype to find the linked application. For example, I wanted to find out what program was used to run Perl programs on my computer. Here are the two commands I typed, shown in boldface, and the results printed by CMD:

C:\book\10>assoc .pl
.pl=Perl
C:\book\10>ftype Perl
Perl="D:\Perl\bin\perl.exe" "%1" %*

goto label
goto :EOF

Directs CMD to jump to the line in the batch file starting with :label and to continue reading statements from that point. Goto :EOF jumps to the end of the file and, in effect, terminates the batch file. Exit /B does the same thing.This is used to terminate batch processing and to exit from a batch file subroutine started with the call statement.

if condition command1 [else command2]
or
if condition (
   commands...
) [else (
   commands...
)]

The if command is used mostly in batch files to perform commands based on conditions encountered as the batch program runs. If, call, and goto are what make the batch file language a real programming language.

If commands can execute one or more commands if the condition test is true.An optional else clause lets you specify a command to run if condition is not true.

md foldername

The md command creates a new directory (folder).The folder name can be a fully qualified path such as c:\musicfiles, or it can be specified relative to the current directory.

When command extensions are enabled, which is the default, md creates any intermediate directories in the path, if they do not already exist.This is another big improvement in CMD over COMMAND.COM. For example,

md "c:\musicfiles\folk\baguette quartette"

works even if c:\musicfiles does not already exist.

Note If the directory you are creating contains spaces in the name, you must enclose the foldername argument in quotation marks. If you omit the quotation marks, CMD ignores anything on the command line after the first space.

mkdir foldername

Mkdir is identical to the md command and takes the same arguments.

move [/y|/-y] [drive:] [path]filename[,...] destination

or

move [/y|/-y] [drive:] [path]foldername newname

The move command moves files from one folder or drive to another, and it can also rename directories.

When moving files, move has the same effect as dragging the files to a new location with Windows Explorer. If the files are moving to a new directory on the same drive, they are not physically copied;Windows needs only to alter the directory entries. If the files are being moved from one drive to another, move copies the files to the new location and then deletes them from the original drive.The filename argument or arguments can include wildcards to move groups of files.The destination argument should be the path to the new folder, or if you are only copying one file, a path including a new filename.

The /y argument makes move silently overwrite any existing files of the same name in the destination folder. If /-y is specified, move prompts before overwriting.The default behavior is to prompt if move is entered from the command line and not to prompt if move is used in a batch file, unless the default is changed by the COPYCMD environment variable or overridden by /y or /-y on the command line. See the copy command earlier in this section for information about COPYCMD.

The second form of the command simply renames a directory to maintain compatibility with older versions of Windows. Because CMD still implements the old meaning of move, you must use wildcards if you want to move all files in a folder. Here are two examples:

  • The command move c:\temp\*.* datafiles moves all files in c:\temp into datafiles, which is interpreted as a subfolder of the current directory.
  • The command move c:\temp datafiles renames c:\temp to c:\datafiles.

Note: On Windows 7, Vista, and XP, the rename command can rename directories, so I recommend you use rename instead of move for this purpose.

path pathlist

Sets the search path to pathlist, a list of folder pathnames separated by semicolons. The path command with no arguments prints the current path.You can also set the path by assigning the pathlist value to the environment variable PATH in a set statement. If there are spaces in any of the names, the name should be enclosed in quotes, as in this example:

path "c:\program files\microsoft office";c:\windows\system32;c:\windows

The PATH value is used by DOS and Windows programs, so if you use DOS programs, you should use only the short 8.3 version of each name in the path. For example, the setting

path c:\progra~1\micros~1;c:\windows\system32;c:\windows

specifies the same list of folders but is compatible with both DOS and Windows programs.

pause

The pause command is used in batch files to let the user read some output before continuing. It prints the famous message "Press any key to continue" in the Command Prompt window and waits for the user to press...well, any key except Ctrl+C or Ctrl+Break, which terminate the batch file.

In new batch files, you might want to use the set /p command to print a more friendly message.

popd

(See pushd.)

prompt [text]

Sets the prompt displayed in the Command Prompt window before each command line to text. If the prompt command is used without any arguments, the prompt is set back to the default setting, $p$g.

I don't have the space to describe all the prompt options in detail here, but you can get a listing by typing prompt /?. If you regularly work with many computers, the prompt setting

prompt %computername%\%username% $p$g

can help you remember with which machine you're working at any given moment.

pushd path
popd

Changes the current directory to the specified path.The previous current drive and directory are remembered, and popd restores the previous path. Pushd saves as many directory changes as you care to make, and each popd returns to the directory in effect before the corresponding pushd. Unlike with cd, if the path specified to pushd contains a drive letter, the current drive is changed as well.

When command extensions are enabled, you can specify a network path (for example, \\server\sharename\path) in a pushd command, and it automatically maps a drive letter to the network path, starting with the letter Z and working backwards. Popd automatically deletes the temporary drive mappings.

rd [/s] [/q] path

The rd command removes the directory named path. You can delete a folder, including all of its files and subfolders, by specifying the /s option.This is very dangerous because the files are deleted immediately and are not moved into the Recycle Bin. Be careful when using /s.As a precaution, CMD prompts you to confirm whether you really do want to delete the entire subdirectory tree.You can add /q on the command line to eliminate this prompt.

Without /s, the specified directory must be empty; otherwise, the command print an error message and not delete the directory.

Tip If you attempt to delete an apparently empty directory with rd but Windows complains that the directory is not empty, look for hidden files or folders by typing dir /ah path.

rem text

Allows you to enter a remark (comment) in a batch file.The text is ignored. Special characters such as |, >, <, and & are also ignored after rem, so you can use these characters in the remark.

ren [path]oldname newname

Same as rename.

rename [path]oldname newname

Renames a file or folder from oldname to newname. If the file or folder is not in the current directory, you can specify its path. Note that newname must not include a path.

rmdir

Rmdir is the same as rd and takes the same arguments.

set [name[=[value]]]
set /a expression
set /p name=promptstring

Sets and displays environment variables.The basic set command has several useful variations:

Command 	Result
set 		Displays the list of all environment variables.
set name 	Displays any variable(s) starting with the
                letters name.
set name= 	Deletes the variable name.
set name=value 	Sets the variable name to the specified value.
                Value is taken literally-do not put spaces after
                the = sign and do not use quotation marks unless
                you want those characters recorded in the variable.

You can use environment variable substitution in a set command. For example, to add c:\batchfiles to the beginning of the existing PATH value, you could use this command:

set path=c:\batchfiles;%path%

You can insert special characters, such as >, <, &, and |, into environment variables, but you must use ^ before them to prevent them from being interpreted as redirection commands or command separators. For example,

set envvar=some^|text

defines an environment variable named envvar with the value some|text.

With command extensions enabled, the set command lets you perform numerical calculations and prompt for input. For information on calculating with set, see "Performing Numerical Calculations in Batch Files," later in this tutorial.

setlocal [ENABLEEXTENSIONS|DISABLEEXTENSIONS]
    [ENABLEDELAYEDEXPANSION|DISABLEDELAYEDEXPANSION]
commands

endlocal

Setlocal saves and restores the batch file environment state. Setlocal saves a record of all environment variables, the current drive letter, the current working directory of all drives, and the state of command extensions and delayed environment expansion. Endlocal restores these settings to their previous values.The optional arguments to setlocal let you enable or disable the command extensions and/or delayed expansion.

The settings revert to the previous state after endlocal or at the end of the batch file.This means that you cannot use setlocal in a batch file that is to change environment variables that remain changed when the batch file ends and the command prompt returns.

shift [/n]

This command shifts the batch file arguments to the left.The optional argument /n lets you start shifting at argument number n, leaving the lower-numbered arguments alone.

The shift command is used when you want to process a variable number of arguments given to a batch file; your batch file can process argument %1, shift, and repeat the process until the argument is blank.

start "title" [/Dpath] [/I] [/MIN | /MAX]
    [/SEPARATE | /SHARED] | [/AFFINITY value] |
    [/LOW | /BELOWNORMAL | /NORMAL | /ABOVENORMAL |
    /HIGH | /REALTIME]
    [/WAIT] [/B] command [arguments]

Starts a command in a new window.The specified command can be a Windows program, a console program, or even the name of a document file, in which case CMD starts the associated application. If start is used in a batch file, the batch file continues without waiting for the program to exit.

Tip This is an incredibly useful command. You can type a command such as start somefile.doc to run Microsoft Word and open the named file. How great is that?!

Optional command-line parameters control how the program is run:

ParameterDescription
"title"Sets the window title to the specified string. By default, the name of the program file is used.
/DpathStarts the program in the specified directory.
/IStarts the program with the default initial environment variable settings, rather than with a copy of the current settings.
/MINStarts the window minimized.
/MAXStarts the window maximized.
/SEPARATEIf the program is a 16-bit Windows program, this parameter starts it in a separate memory space with its own copy of the Win16 environment.
/SHAREDIf the program is a 16-bit Windows program, this parameter starts it in the shared memory space where it can interact with other 16-bit Windows programs. (/SEPARATE and /SHARED are not applicable on 64-bit Windows systems because they cannot run 16-bit Windows programs.)
/AFFINITY valueOn a multicore or multiprocessor system, it limits the process to run on processors corresponding to the bits set in the hexadecimal value. For example, value 1 restricts the process to the first processor, whereas value 3 limits it to the first two processors.
/LOW
/BELOWNORMAL
/NORMAL
/ABOVENORMAL
/HIGH
REALTIME
Runs the program in the indicated priority class. Be cautious of using /REALTIME, which lets the program run to the exclusion of nearly anything else. If the program is ill-behaved, you might have a difficult time running the Task Manager to stop it.
/WAITMakes the start command wait until the program exits before continuing.This is useful in batch files to let you run a program with an altered priority.
/BFor command line (console) programs, this parameter runs the program in the current window. Ctrl+C handling is disabled by default, but Ctrl+Break should still work if you need to interrupt the program.
time [/t | newtime]

With no arguments, time displays the current time of day and requests that you type in a new time.You can press Enter to keep the current setting.With /t on the command line, time displays the time without prompting for a replacement.This is meant to be used in batch files. For example, to record the date and time that a batch file was run, you might use the following commands:

echo batch file run on >batchlog.txt
date /t >>batchlog.txt
time /t >>batchlog.txt
echo. >>batchlog.txt
other commands >>batchlog.exe

However, it might be neater to print both the date and the time on the same line with the statement echo %date% %time% >>batchlog.txt.

You can also set the time by specifying the new clock setting on the command line.The time must be formatted according to the localized time format.You enter times with or without seconds, in 24-hour format or in AM/PM format, as in these examples:

time 18:58
time 6:58:20 PM
title [string]

Sets the title of the current Command Prompt window to the specified string. By default, the title is Command Prompt, and when a program is running, it's Command Prompt - command line.

type [path]filename

Writes the specified file to the standard output. Normally this means that the file is displayed in the Command Prompt window. (For long files, the more command is a better choice because it displays the file a page at a time.) You can also use type to append one file onto another. For example, the following commands run a ping command, display the result, and also add the result to a log file that accumulates new information every time the commands are run:

@echo off
cls
echo Testing connection to mycompany.com...
ping www.mycompany.com 2>&1 >ping.out
echo The results are:
type ping.out

echo. >>ping.log
echo Test run at >>ping.log
date /t >>ping.log
time /t >>ping.log
type ping.out >>ping.log
del ping.out

ver
displays the version of Windows on your computer.

verify [on | off]

Verify on instructs Windows to read back all data written to the hard disk by application programs immediately after writing, to ensure that the data can be read correctly.This is especially useful when writing to floppy or other removable disks. Verify off disables read-after-write checking. Verify with no arguments displays the current setting; the default is off.You can specify the /V option with the copy command to enable verification just for the copy operation.

vol [drive:]

Displays the label and volume serial number for a disk drive. By default, vol displays the information for the current drive.You can specify an alternative drive on the command line.

[Previous] [Contents] [Next]