6.4. Alphabetical Reference to DOS Commands
Most of the following commands are not standalone applications (like those listed in Chapter 4), but rather internal functions of the Command Prompt ( cmd.exe ) application. This restricts their use only to the Command Prompt application. (They won't be recognized by the Address Bar or by Start Run.) Some items that are standalone programs, but are normally used only in the Command Prompt window, such as xcopy.exe and move.exe , are listed here rather than in Chapter 4.
cd or chdir |
Display the name of or change the current working directory (folder).
cd [/d] [ directory ]
chdir [/d] [ directory ]
With no arguments, cd displays the full pathname of the current directory. Given the pathname of an existing directory, it changes the current directory to the specified directory.
If directory is on a different drive (for example, if the current directory is c:\dream and you type cd d:\nightmare ), the current working directory on that drive is changed, but the current working drive is not. To change the current drive, use the /d parameter, or simply type the letter followed by a colon , by itself, at the prompt (see the examples below).
Pathnames can be absolute (including the full path starting with the root) or relative to the current directory. A path can be optionally prefixed with a drive letter. The special paths .. and ... (and so on) refer to the parent and grandparent of the current directory, respectively.
If the current drive is C: , make c:\temp\wild the current directory:
C:\> cd \temp\wild C:\temp\wild>
Note how the current working directory is displayed in the prompt. If the current directory is c:\temp , all that is necessary is:
C:\temp> cd wild C:\temp\wild>
Change to the parent directory:
C:\more\docs\misc> cd .. C:\more\docs>
Change to the root directory of the current drive:
C:\Windows\Desktop\> cd \ C:\>
Change to another drive:
C:\> cd /d d:\ D:\>
or simply:
C:\> d: D:\>
The chdir and cd commands are functionally identical.
The "current working directory" only has meaning in the current Command Prompt session and any other Command Prompts or applications launched from that window. If you open a new Command Prompt window, it will start over with it's default (set in the properties of the Windows Shortcut).
The current directory is shown in the prompt; see "prompt", later in this chapter, for information on changing the information displayed.
cls |
Clear the DOS window and buffer, leaving only the command prompt and cursor.
Type cls at the prompt to clear the screen and the screen buffer (see Section 6.1, earlier in this chapter), which is useful for privacy concerns or simply reducing clutter.
The difference between using cls and simply closing the current Command Prompt window and opening a new one, is that your working environment (such as the current directory) is preserved with cls .
cls is also useful in complex batch filesfor clearing the screen after one set of interactions or command output. The name cls (Clear Screen) refers to the old days when DOS owned the whole screen.
copy |
Copy one or more files to another location.
copy source destination
copy [/a /b] source [/a /b] [+ source [/a /b] [+ ...]] [ destination [/a /b]] [/v] [/y /-y] [/d] [/z]
copy makes a complete copy of an existing file. If another file by the same name exists at destination , you will be asked if you want to overwrite it.
Omit the destination to copy the specified files to the current working directory. If the file (or files) to be copied is in a different directory or on a different disk, you can omit the destination filename. The resulting copy or copies will have the same name as the original.
You can use the special device name con (or con :) in place of either the source or destination filename to copy from the keyboard to a file (or from a file to the screen).
copy accepts the following parameters and options:
Specifies that the file to copy is in ASCII format
Specifies that the file to copy is a binary file
Verifies that new files are written successfully by comparing them with the originals
Suppresses prompting to confirm you want to overwrite an existing destination file
Enables prompting to confirm you want to overwrite an existing destination file with the same name (default)
Allow the new file to be decrypted (NTFS volumes only)
Copies networked files in restartable mode
Copy the file temp.txt from C:\ to d:\files (all three examples do the same thing):
C:\> copy c:\temp.txt d:\files\temp.txt C:\> copy c:\temp.txt d:\files C:\> copy temp.txt d:\files
The third sample above works here because the source file is located in the current director. Here's another way to do it:
C:\> d: D:\> cd \files D:\files> copy c:\temp.txt
Copy all the files from the directory d:\Cdsample\Images to the current directory, giving the copies the same names as the originals:
C:\> copy d:\cdsample\images\*.* C:\> copy d:\cdsample\images\*.* .
Copy the file words.txt in the current directory to d:\files , renaming it morewords.txt :
C:\> copy words.txt d:\files\morewords.txt
Copy all of the files in the current directory to d:\files (all three examples do the same thing):
C:\> copy *.* d:\files C:\> copy .\*.* d:\files C:\> copy . d:\files
The copy command is easier to use, but xcopy (discussed later in this chapter) is more powerful and flexible.
It is also possible to use the copy command to concatenate (combine) files. To concatenate files, specify a single file for the destination, but multiple files for the source (using wildcards or file1 + file2 + file3 format):
copy mon.txt+tue.txt+wed.txt report.txt
You can specify a relative or absolute path (including disk names and/or UNC paths) or use a simple filename. When concatenating, if no destination is specified, the combined files are saved under the name of the first specified file.
When attempting to concatenate files, copy expects ASCII files by default, so in order to concatenate binary files, you need to use the /b option. The reason for this is that binary files typically contain one or more bytes outside the normal ASCII printable range (i.e., 32 through 127).
The con device (console) can also be used in conjunction with copy . To create a new text file by typing its contents directly, first enter:
C:\> copy con mystuff.txt
then type the text to be saved into the file. When you're done, type Ctrl-Z and press Enter. All text typed from the keyboard in this example is then saved as mystuff.txt .
Here's how to copy the contents of the file mystuff.txt to the screen (see also "type"):
C:\> copy mystuff.txt con
Binary file copy is assumed for normal copying, but the /b option should be used when appending one binary file to another, as in:
C:\> copy file1+file2 newfile /b
By default, when concatenating, both source and destination files are assumed to be ASCII format, since binary files can seldom be usefully concatenated due to internal formatting.
You can substitute a device (e.g., COM1) for either the source or the destination. The data is copied in ASCII by default.
copy doesn't copy files that are bytes long; use xcopy to copy these files.
copy , move , and xcopy will prompt you before overwriting an existing file, unless you specify a command line parameter instructing them to do otherwise . To change the default, set the copycmd environment variable to /y . To restore the default behavior, set copycmd to /-y . See "set" for details.
date |
Display or set the system date.
date [/t date ]
Date is essentially a holdover from the very early days of DOS when the user was required to enter the system date and time every time the computer was started. Now it's essentially included as a way to set the data from the command line; the preferred method is to use Control Panel Date and Time.
If you type date on the command line without an option, the current date setting is displayed and you are prompted for a new one. Press Enter to keep the same date.
Date accepts the following options:
Specifies the date. Use the mm-dd- [ yy ] yy format. Values for yy can be from 80 through 99; values for yyyy can be from 1980 through 2099. Separate month, day, and year with periods, hyphens, or slashes .
Displays the current date without prompting for a new one.
The date format depends on settings in Control Panel Regional and Language Options.
Windows records the current date for each file you create or change. This date is listed next to the filename in the dir directory listing.
The date display format for most applications can be changed in Control Panel Regional and Language Options Regional Options tab Customize, but this doesn't affect the output of the DOS date command.
"time"
del or erase |
Delete one or more files.
del [/p] [/f] [/s] [/q] [/a: attributes ] filename
erase [/p] [/f] [/s] [/q] [/a: attributes ] filename
The del command is used to delete one or more files from the command line without sending them to the Recycle Bin.
The del options are:
Specifies the file(s) to delete. If you do not specify the drive or path, the file is assumed to be in the current directory. You can use standard * and ? wildcards to specify the files to delete.
Prompts for confirmation before deleting each file.
Forces deletion of read-only files.
Delete specified files in all subdirectories (when using wildcards).
Quiet mode; do not prompt if filename is *.* .
Selects files to delete based on attributes (read-only, hidden, system, or archive). See "Attrib" in Chapter 4 for more information on attributes.
Delete the file myfile.txt in the current directory:
C:\> del myfile.txt
Delete the file myfile.txt in the c:\files directory:
C:\> del c:\files\myfile.txt
Delete all files with the pattern myfile .* (e.g., myfile.doc , myfile.txt , etc.) in the current directory, but prompt for each deletion:
C:\> del c:\files\myfile.* /p
The del and erase commands are functionally identical.
Using the del command to delete a file does not move it to the Recycle Bin. In other words, you can't get a file back once you use the del command, unless you have a special " unerase " disk recovery utility.
dir |
Display a list of files and subdirectories in a directory (folder).
dir [ filename ] [/b] [/c] [/d] [/l] [/n] [/p] [/q] [/s] [/w] [/x]
[/4] [/a: attributes ] [/o: sortorder ] [/t: timefield ]
Without any options, dir displays the disk's volume label and serial number, a list of all files and subdirectories (except hidden and system files) in the current directory, file/directory size, date/time of last modification, the long filename, the total number of files listed, their cumulative size , and the free space (in bytes) remaining on the disk.
If you specify one or more file or directory names (optionally including drive and path, or the full UNC path to a shared directory), information for only those files or directories will be listed.
Wildcards (* and ?) can be used to display a subset listing of files and subdirectories.
dir accepts the following options:
Display only files with/without specified attributes (using - as a prefix specifies "not," and a colon between the option and attribute is optional). See "Attrib" in Chapter 4 for more information on attributes.
Use bare format (no heading information or summary). Use with /s to find a filename.
Display compression ratio of files on Dblspace or DrvSpace drives , assuming 16 sectors/cluster.
Same as /w , except files are sorted vertically.
Use lowercase.
List files in a "new" Unix-like display, where filenames are shown on the right.
List files in sorted order (using - as a prefix reverses the order, and a colon between the option and attribute is optional):
By date and time (earliest first)
By extension (sorted alphabetically )
Group directories first
By name (sorted alphabetically)
By size (smallest first)
Pause after each screenful of information; press any key to continue.
Display the owner of each file.
Include all files in all subdirectories, in addition to those in the current directory.
Control which time is used when sorting:
Created
Last accessed
Last modified (written)
Wide list format. File and directory names are listed in five columns and are sorted horizontally. Use /d instead to sort vertically.
Include the "short" 8.3 versions of long filenames. For example, Sam's File.txt has an alternate filename, samsfi~1.txt , to maintain compatibilty with older applications.
Display the listed years as four digits. By default, two-digit years are displayed.
Display all files in the current directory:
C:\> dir
Display all files in the current directory that end with the .txt extension:
C:\> dir *.txt
Display all files, listing years in four digits and pausing for each screenful:
C:\> dir /4 /p
Display all files, sorted by date and time, latest first:
C:\> dir /o-d
Display only directories:
C:\> dir /ad
List all files on disk, sorted by size, and store output in the file allfiles.txt :
C:\> dir \ /s /os > allfiles.txt
List the contents of the shared folder cdrom on machine bubba :
C:\> dir \bubba\cdrom
To change the default sort order, set the dircmd environment variable to the same value you'd use with the /o parameter. See "set" for details.
When using a redirection symbol (>) to send dir output to a file or a pipe () or to send dir output to another command, you may want to use /b to eliminate heading and summary information.
|
One of Windows Explorer's weaknesses is that there's no way to print a directory listing or save a directory listing into a file. However, the dir command with some clever redirects will do the job.
To print out a sorted directory listing of all files in the Windows directory:
C:\> dir c:\windows /oa > lpt1
To create a file containing the directory listing of the same directory:
C:\> dir c:\windows /oa > c:\myfiles\windows.txt
Actually, dir can be used to fix this weakness of the Explorer. See Windows 98 Annoyances (O'Reilly) for details on how to give the Explorer a Print-Dir facility.
Files and folders that are hidden (see "Attrib" in Chapter 4) will not show up in dir listings by default. However, if you know the name of a hidden directory, there's nothing stopping you from displaying a listing of the contents in that directory.
echo |
Display a string of text; turn command echoing on or off.
echo [on off message ]
Echo is typically used with other commands or in a batch file to display text on the screen. It's also used to control command echoing from batch files.
The following options can be used with echo :
By default, each command in a batch file is echoed to the screen as it is executed. Echo on and echo off toggles this feature. To turn echoing off without displaying the echo off command, use @echo off . The @ symbol in front of any command in a batch file prevents the line from being displayed.
Types the message you'd like displayed to the console (screen).
To display an ordinary message, use the following:
echo Hello World!
To display a blank line, use one of the following (all equivalent):
echo. echo, echo"
(Note the absence of the space between the echo command and the punctuation; you can also use a colon, semicolon, square brackets, backslash, or forward slash.)
One handy use of echo is to answer y to a confirmation prompt such as the one del issues when asked to delete all the files in a directory. For example, if you wanted to clear out the contents of the \temp directory from a batch file, you could use the following command:
echo y del c:\temp\*.*
or even:
echo y if exists c:\temp\*.* del c:\temp\*.*
This construct works because the pipe character takes the output of the first command and inserts it as the input to the second.
Announce the success or failure of a condition tested in a batch file:
if exist *.rpt echo The report has arrived.
It's a good idea to give the user usage or error information in the event that they don't supply proper arguments to a batch file. You can do that as follows :
@echo off if (%1) == ( ) goto usage . . . :usage echo You must supply a filename.
"type"
exit |
End the current Command Prompt session and close the window.
exit [/b] [ exitcode ]
Typing exit has the same effect as closing the Command Prompt window with the [x] button.
exit accepts the following options:
If exit is used from within a batch file, it will close the current Command Prompt window. Specify /b to exit the batch file but leave cmd.exe running.
Specifies a numerical "exit code" number that is passed to the application or process that launched the Command Prompt or started the batch file. Exitcode is typically used when one batch file runs another batch file and wishes to report to the "parent" batch file whether successful or not.
If you start a new Command Prompt session by typing cmd in an open Command Prompt window, exit will end that session. However, since the "parent" session is still active, the window won't close until you type exit again.
find | \Windows\Command\find.exe |
Search in one or more files for text.
find [/v] [/c] [/n] [/i] [/offline] " string " [ filename [ ...]]
After searching the specified files, find displays any lines of text that contain the string you've specified for your search. find is useful for searching for specific words (strings) in files, but don't get it confused with Start Search For Files or Folders (See "Windows Explorer" in Chapter 4), which is capable of searching for text, files, directories, etc., and has many other capabilities that the find command doesn't have.
The find options are:
The text to look for, enclosed in quotation marks.
The file(s) in which to search. Although wildcards (*, ?) are not supported, multiple filenames can be specified as long as they are separated with commas. If filename is omitted, find searches text typed at the prompt or piped from another command via the pipe character ( ), as described in Section 6.3, earlier this chapter.
Displays only the count of lines containing the string.
Ignores the case of characters when searching for the string.
Displays line numbers with the displayed lines.
Displays all lines not containing the specified string.
Includes files with the offline attribute set (that otherwise would be skipped ).
Search for "redflag" in myemployees.txt :
C:\> find "redflag" myexployees.txt
Count occurrences of the word "deceased" in myemployees.txt :
C:\> find /c "deceased" myexployees.txt
Search the current directory for the string "cls" in all .bat files and store the result in the file cls.txt (note that >> rather than > is necessary when redirecting the output of a for loop):
C:\> for %f in (*.bat) do find "cls" %f >> cls.txt
You can search through multiple files by specifying each file to search on the command line, but unfortunately, wildcards (* and ?) are not accepted in the filename. To search for a string in a set of files, however, it's possible to use the find command within a for loop structure. If redirecting for to a file, use >> rather than > (see the earlier example).
If a filename is not specified, find searches the text input from the "standard" source (usually the keyboard), a pipe, or a redirected file.
If you have a Unix background, you might be tempted to try something like:
dir c:\ /s /b find "chap"
to search the contents of all files with "chap" in their names, but in fact, all you'd be doing is running find on the list of filenames, not on their contents.
find won't recognize a string that has a carriage return embedded in it. For example, if "chapter" is at the end of the line and "05" on the next, find won't report a match on "chapter 05."
md or mkdir |
Create a new directory (folder).
md [ drive :] path
mkdir [ drive :] path
Windows XP, like its predecessors, uses a hierarchical directory structure to organize its filesystem. On any physical disk, the filesystem begins with the root directory, signified by a lone backslash.
md and mkdir accept the following option:
Specifies the directory to create.
Create a subdirectory named harry in the current directory:
C:\tom\dick> md harry
Create a new directory called newdir under the c:\olddir directory:
C:\> md c:\olddir\newdir
If c:\olddir doesn't exist, it will be created as well.
Create two new directories, c:\rolling and c:\stones :
C:\> md rolling stones
Create a single new directory, c:\rolling stones :
C:\> md "rolling stones"
(Enclose directory names in quotation marks to accommodate spaces).
The md and mkdir commands are functionally identical.
You can also create new folders in Windows Explorer by going to File New Folder.
You may indicate an absolute or relative path for the path parameter. When absolute, the new directory is created as specified from the root directory. When relative, the directory is created in relation to the current directory.
more | \windows\system32\more.com |
Display the contents of a file with the output of another command, but pause the display so that only one screen of text is shown at a time.
more /e [/c] [/p] [/s] [/tn] [+n] [ filename ]
more [/e [/c] [/p] [/s] [/tn] [+n]] < filename
{some other command} more [/e [/c] [/p] [/s] [/tn] [+n]]
more displays one screen of text at a time. more is often used as a filter with other commands that may send a lot of output to the screen (i.e., to read standard input from a pipe or redirected file). Press any key to see the next screenful of output. Press Ctrl-C to end the output before it is done.
more accepts the following options:
Specifies the name of a file to display.
Clears the screen before displaying file.
If the /e option is specified, the following additional extended commands are available at the More prompt:
Displays next n lines.
Skips next n lines.
Displays next page.
Displays next line.
Displays next file.
Quits.
Shows line number.
Shows help.
Expands form-feed characters.
Squeezes multiple blank lines into a single line.
Expands tabs characters to n spaces (default 8).
Starts display of the file at line n .
Specifies the name of a file to display.
Display the contents of \Windows\readme.txt and pause for each screenful of text (both of the following examples have the same effect):
C:\> more c:\windows\readme.txt C:\> type c:\windows\readme.txt more
Keep the output of dir from scrolling off the screen before you can read it:
C:\> dir c:\windows more
Some commands (like dir ) have a /p option that "pages" the output (i.e., dir more is the same as dir /p ), but many do not.
"type"
move |
Move files and directories from one location to another.
move [/y /-y] filename [,...] destination
move works like copy , except that the source is deleted after the copy is complete. Filename can be a single file, a group of files (separated with commas), or a single file specification with wildcards.
The move options are:
Specifythe location and name(s) of the file or files you want to move. Wildcards (*, ?) are supported.
Specify the new location of the file. The destination parameter can consist of a drive, a directory name, or a combination of the two. When moving one file, destination may include a new name for the file.
Suppress prompting to confirm creation of a directory or overwriting of the destination. This is the default when move is used in a batch file.
Cause prompting to confirm creation of a directory or overwriting of the destination. This is the default when move is used from the command line.
Move myfile.txt from the current directory to d:\files :
C:\> move myfile.txt d:\files\
Same, but rename the file to newfile.txt :
C:\> move myfile.txt d:\files\newfile.txt
Change the name of the directory d:\files to d:\myfiles :
D:\> move d:\files myfiles
copy , move , and xcopy will prompt you before overwriting an existing file, unless you specify a command line parameter instructing them to do otherwise. To change the default, set the copycmd environment variable to /y . To restore the default behavior, set copycmd to /-y . See "set" for details.
"ren or rename"
path |
Set or display the command search path.
path [ path1 ][; path 2][; path 3][;...]
When you type an executable filename at the command prompt (as opposed to an internal DOS command), Windows starts by looking in the current directory for a file that matches. If no matching file is found, Windows then looks in a series of other foldersthese folders are known collectively as the path or the command search path.
The path statement is used to define additional directories to be included while searching for files. The path consists of a series of absolute directory pathnames, separated by semicolons. No spaces should follow each semicolon, and there should be no semicolon at the end of the statement. If no drive letter is specified, all pathnames are assumed to be on the boot drive.
Type path without any arguments to display the current command search path. The default path in Windows XP is c:\windows\system32 ; c:\windows ; c:\windows\system32\wbem .
When you type the name of a command, DOS looks first in the current directory, and then in each successive directory specified in the path. Within each directory, it will look for executable files by their extension in the following order: .com , .exe , .bat . Windows searches your path for certain other file types (i.e., .dll or .ocx ) as well, although most cannot be executed from the command line (see Notes for more information).
Specify the directories c:\Stuff and d:\Tools in the path:
C:\> path c:\stuff;d:\tools
However, this will replace the path with these two folders. To add these folders to the existing path, type the following:
C:\> path %path%;c:\stuff;d:\tools
The path is actually an environment variable and the path command is merely a shortcut for the following:
set path=%path%;c:\stuff;d:\tools
See "set", later in this chapter, for more information environment variables and details on setting global environment variables that don't expire when the Command Prompt window is closed.
Unlike some earlier versions of Windows, XP recognizes long folder names in the path (e.g., c:\Program Files ). If the folder name has a semicolon in it, you may still have to use the short names equivalent (e.g., c:\PROGRA~1 ).
Type path ; to clear all search path settings and direct Windows to search only in the current directory.
The order of directories in the search path is quite important. For example, you might run MKS Toolkit, a set of third-party tools that brings Unix functionality to Windows systems. MKS normally stores its files in \MKSNT , but if you have the path set as follows:
path=C:\;C:\MKSNT;C:\Windows;C:\Windows\Command
you won't be able to run a DOS command like find without typing its full pathname because the MKS find command will be found and executed first.
Windows also searches the path for Windows shortcuts, but the usage might be nonintuitive. To launch a shortcut named Widget, for example, you'd have to type widget.lnk at the prompt.
All of the supported file types are specified in the PATHEXT environment variable (see "set", later in this chapter). By default, Windows searches the path for the following extensions: .com, .exe, .bat, .cmd, .vbs, .vbe, .js, .jse, .wsf, and .wsh .
prompt |
Change the appearance of the prompt.
prompt [ text ]
Type prompt by itself (without text ) to reset the prompt to its default setting.
The prompt options are:
Specifies a new command prompt. Text can contain normal characters and the following special codes:
Carriage return and linefeed
Dollar sign ( $ )
Ampersand ( & )
Pipe ( )
Left parenthesis ( ( )
Current date
Escape character (ASCII code 27)used to provide extended formatting
Right parenthesis ( ) )
Greater-than sign ( > ), commonly known as the caret
Backspace (erases previous character)
Less-than sign ( < )
Current drive
Current drive and path
Equal sign ( = )
Space
Current time
Windows version number
Specify the current drive and directory followed by the greater-than sign ( > )the default prompt in Windows XP:
C:\> prompt $p$g
Specify the drive and directory on one line and the date, followed by the greater-than sign ( > ) on another:
C:\> prompt $p$_$d$g
Specify the drive only, followed by the greater-than sign ( > ), which was the default prompt on early versions of DOS:
C:\> prompt $n$g
The current prompt setting is actually stored in the environment, and the prompt command is merely a shortcut for the following:
set prompt=$p$g
See "set", later in this chapter, for more information environment variables and details on setting global environment variables that don't expire when the Command Prompt window is closed.
rd or rmdir |
Remove (delete) a directory.
rd [/s] [/q] path
rmdir [/s] [/q] path
Unlike in Windows Explorer, files and folders are deleted differently; if you try to use del to delete a directory, it will simple delete all the files in the directory, but the directory itself will remain . rd is used to delete empty directories and, optionally, to delete directories and all of their contents.
rd accepts the following options:
Specifies the directory to delete.
Removes all files and subdirectories of the specified directory.
Quiet mode; don't prompt when using /s .
Delete the empty subdirectory called newdir located in the c:\olddir directory:
C:\> rd c:\olddir\newdir
Delete the directory Online Services and all of its contents within the current directory, c:\Program Files :
C:\Program Files> rd /s "online services"
Note that quotes must be used with rd for folders with spaces in their names.
The rd and rmdir commands are functionally identical.
As a safety feature, attempting to delete a directory that is not empty without including the /s option will display the message, "The directory is not empty."
rd with the /s option takes the place of the deltree command found in earlier versions of Windows, but no longer included in Windows XP.
If you try to delete the current directory, you'll get the following error: "The process cannot access the file because it is being used by another process." In this case, you'll have to change to a different directory first.
ren or rename |
Rename a file or directory.
ren [ filename1 ] [ filename2 ]
rename [ filename1 ] [ filename2 ]
Use ren to rename any file or directory. Unlike Windows Explorer, though, ren is capable of renaming several files at once (via wildcards 8 and ?).
The ren options are:
The name of the existing file or directory.
The new name to assign the file or directory.
Rename myfile.txt to file.txt :
C:\> rename myfile.txt file.txt
Rename chap 5.doc to sect 5.doc : (the following two methods are identical):
C:\> ren "chap 5.doc" "sect 5.doc" C:\> ren chap?5.doc sect?5.doc
Each of these examples represent different ways to rename files with spaces in their names. In addition to the standard quotation marks, in certain circumstances, you can use wildcards to avoid the spaces problem. Here, both chap 5.doc and sect 5.doc have spaces in the fifth character position, so the single wildcard character (?) can be used.
Rename the files chap1.doc , chap2.doc , etc. to revchap1.doc , revchap2.doc , etc.:
C:\> ren chap*.doc revchap*.doc
ren can be a convenient way to rename the filename extensions of several files at once, as well:
C:\> ren *.txt *.rtf C:\> ren *.htm *.html C:\> ren *.mpeg *.mpg
The ren and rename commands are functionally identical.
You can't move files from on directory to another with ren ; use move instead.
The file's Last Modified date is not changed when using ren .
"move"
set |
Display, assign, or remove environment variables.
set [ variable [=[ string ]]]
set /p variable =[ promptstring ]
set /a expression
The environment is a small portion of memory devoted to the storage of a few values called environment variables. set is used to manipulate environment variables from the command line, but since the Command Prompt's environment is reset when its window is closed, the usefulness of set is fairly limited.
To affect more permanent changes to environment variables, go to Control Panel System Advanced tab Environment variables. This window should be fairly self-explanatory; the variables in the upper listing are for the current user and variables in the lower listing apply to all users. Some environment variables, such as the Temp user variable, are assigned with respect to other variables, like this:
%USERPROFILE%\Local Settings\Temp
where %USERPROFILE% (note the percent signs ( %) on either side) signifies the USERPROFILE variable, which represents the path of the current user's home directory. See "path", earlier in this chapter, for another example of this usage.
In addition to providing a simple means of interapplication communication, environment variables are also useful for storing data used repeatedly in a batch file (see Section 6.5, later in this chapter).
Type set without options to display all of the current environment variables. Type set with only a variable name (no equal sign or value) to display a list of all the variables whose prefix matches the name.
The set options are:
Specifies the variable name. When assigning a new variable, the case used is preserved. But when referencing, modifying, or deleting the variable, variable is case-insensitive. If variable is specified by itself, its value is displayed. If variable is specified by itself with an equal sign, the variable is assigned an empty value and deleted. Variable cannot contain spaces.
Specifies a series of characters to assign to variable . As stated above, this can contain references to other variables by surrounding them with preceding and trailing percent signs ( % ).
Specifies that variable will be assigned by text input from the user, rather than string . As stated above, this can contain references to other variables with preceding and trailing percent signs ( % ).
The text prompt to display when using the /p option.
Specifies that expression is a numerical expression to be evaluated. If used from the command prompt, set /a will display the final evaluated result of expression , even if you include an assignment operator (such as =) to assign a variable.
When used with the /a option, expression is a collection of symbols, numbers, and variables arranged so that it can be evaluated by set . The following symbols are recognized (in decreasing order of precedence):
Parenthesis for grouping
Unary operators
Arithmetic operators (multiply, divide)
Arithmetic operators (add, subtract)
Logical shift
Boolean "and"
Boolean "exclusive or"
Boolean "or"
Assignment
Expression separator
If you use /a with any of the boolean or modulus operators, you need to enclose expression in quotes. Any non-numeric strings in expression are treated as environment variable names, and their values are converted to numbers during evaluation (zero is used for undefined variables); the percent signs ( % ) are not used here.
Set the variable dummy to the string "not much":
C:\> set dummy=not much
Set the dircmd variable, which instructs the dir command (discussed earlier in this chapter) to sort directory listings by size with the largest first:
C:\> set dircmd=/s /o-s
Append the directory c:\mystuff to the path (see "path", earlier in this chapter); note how the path variable is used on the right side of the equal sign so that its original contents aren't lost:
C:\> set path=%path%;c:\mystuff
Set the prompt (see "prompt", earlier in this chapter) to show the current time, followed by a right angle bracket :
C:\> set prompt=$t>
Display the contents of the variable named dummy (both of the following statements are equivalent):
C:\> set dummy C:\> echo %dummy%
You can also reference environment variables with other commands:
C:\> set workdir=C:\stuff\tim's draft C:\> cd %workdir%
Here the environment variable is used to store a long pathname for quick navigation to a frequently used directory.
Display the values of all variables that begin with the letter H:
C:\> set h
Clear the value of an environment variable, dummy :
C:\> set dummy=
Prompt the user to enter text to be inserted into the dummy variable (typically used in batch files):
C:\> set /p dummy=Enter text here>
Evaluate an arithmetic expression (the two following expressions are not the same):
C:\> set /a 7+(3*4) C:\> set /a (7+3)*4
The results of these two expressions, 19 and 40, respectively, will be displayed. To assign the result to a variables, type the following:
C:\> set /a dummy=7+(3*4)
Even though you're assigning the result variable, the result will still be displayed (unless set is executed from batch file). To suppress the output, type this:
C:\> set /a dummy=7+(3*4) > nul
In addition to any custom environment variables you may use, Windows XP recognizes the following variables (many of which are already defined):
The location of the All Users folder, usually c:\Documents and Settings\All Users .
The location of the Application Data folder, usually c:\Documents and Settings\%USERNAME%\Application Data .
The location of the Common Files folder, usually c:\Program Files\Common Files .
The network name of the computer, set by going to Control Panel System Computer Name tab Change.
The location of the command prompt application executable, c:\Windows\system32\cmd.exe by default.
Whether the copy , move , and xcopy commands should prompt for confirmation before overwriting a file. The default value is /-y . To stop the warning messages, set copycmd to /y .
Specifies the default options for the dir command. For example, setting dircmd to /p will cause dir to always pause after displaying a screenful of output.
The drive letter of the drive containing the current user's home directory, usually c: , used with HOMEPATH .
Along with HOMEDRIVE , the path of the current user's home directory, which is usually \Documents and Settings\%USERNAME% .
The name of the computer as seen by other computers on your network, usually the same as COMPUTERNAME preceeded by two backslashes.
The number of processors currently installed, usually 1. In a multiprocessor system, it can be 2 or 4.
Used to identify the operating system to some applications; for Windows XP, OS is set to "Windows_NT." You may be able to "fool" an older program that is programmed not to run on an NT system by changing this variable temporarily.
The sequence of directories in which the command interpreter will look for commands to be interpreted. See "path", earlier in this chapter.
The filename extensions (file types) Windows will look for in the directories listed in the path (see "path", earlier in this chapter). The default is .COM , .EXE , .BAT , .CMD , .VBS , .VBE , .JS , .JSE , .WSF , and .WSH
The type of processor; set to x86 for Intel-based processors (such as the Pentium 4).
A series of values used by the processor manufacturer to identify the processor.
The location of the Program Files folder, usually c:\Program Files .
The format of the command-line prompt, usually $P$G. See "prompt", earlier in this chapter, for details.
The name of the current command prompt session; usually "Console."
The drive letter of the drive containing Windows, usually C: .
The location of the Windows directory (or more specifically , the name of the folder in which the \Windows\System32 folder can be found), usually c:\windows .
The location where many programs will store temporary files. TEMP and TMP are two different variables, but they should both have the same value; usually set to c:\DOCUME~1\%USERNAME%\LOCALS~1\Temp (short name used to maintain compatibility with older DOS programs).
The name of the domain to which the computer belongs (set by going to Control Panel-System-Computer Name-Change). If no domain is specified, USERDOMAIN is the same as COMPUTERNAME .
The name of the current user.
The location of the current user's home directory, which should be the same as HOMEDRIVE plus HOMEPATH , usually c:\Documents and Settings\%USERNAME% .
The location of the Windows directory, usually c:\windows .
Among the standard environment variables listed above, some represent certain system folders (such as PROGRAMFILES ). These variables only reflect the corresponding settings in the Registry (and elsewhere); changing them will only affect what is reported to applications that use these variables; it won't actually change where Windows looks for these folders.
sort | \windows\system32\sort.exe |
Sort text or the contents of text files in alphanumeric order.
sort [/r] [/+n] [/m kilobytes ] [/l locale ] [/rec recordbytes ]
[/t [ tempdir ]] [/o outputfilename ] [filename]
The sort command sorts text on a line-by-line basis. Each line of the input is ordered alphanumerically and output to the screen (or optionally, stored in a file). By default, sorting starts with the character in the first column of each line, but this can be changed with the /+n option. sort is often used in conjunction with either pipes or output redirection (both discussed earlier in this chapter). That is, you might want to sort the output of another command, and you will often want to redirect the output to a file so that it can be saved. sort takes the following options:
Reverses the sort order; that is, it sorts Z to A and then 9 to 0
Sorts the file according to characters in column n .
Specifies amount of main memory to allocate for the sort operation in kilobytes. The default is 90 percent of available memory if both the input and output are files, and 45 percent of memory otherwise. The minimum amount of memory sort will use is 160 Kb; if the available (or specified) memory is insufficient, sort will split the operation up using temporary files.
Overrides the system default locale (see Control Panel Regional and Language Options). The "C" locale yields the fastest collating sequence, and in Windows XP, is the only choice.
Specifies the maximum number of characters on a line (in a record); the default is 4,096 and the maximum is 65,535.
Specifies the location of the directory used to store temporary files, in case the data does not fit in main memory (see the /m option). The default is to use the system temporary directory.
Specifies a file where the output is to be stored. If not specified, the sorted data is displayed at the prompt. Using the /o option is faster than redirecting output (with the > symbol).
The name (and optionally, full path) of the file to sort.
Display an alphabetically sorted directory (similar to dir /o ):
C:\> dir sort
Sort the contents of a file, data.txt , and store the sorted version in results.txt (the following four examples are all equivalent, although the first is the most efficient):
C:\> sort /o results.txt data.txt C:\> sort data.txt > results.txt C:\> sort /o results.txt < data.txt C:\> type data.txt sort > results.txt
The input to sort should be ASCII text, so that each line can be considered a record of data.
Using the /+n parameter, the lines (records) of the input text may be broken into fields, each beginning a fixed number of characters from the start of the line, facilitating a sort of third column.
Blank lines and leading spaces will be sorted. This can result in many blank lines at the top of the sorted output; you may need to scroll down in an editor to see nonblank lines.
If you do a lot of command-line sorting, you may want to get a Windows version of the Unix sort utility (available as part of the MKS Toolkit; http://www.mkssoftware.com/), which is much more powerful. The Unix sort command lets you define and sort on fields within the line, ignore upper- and lowercase distinctions, and eliminate duplicate lines, among other things.
time |
Display or set the system time.
time [/t time ]
Like date (discussed earlier in this chapter), time is essentially a holdover from the very early days of DOS when the user was required to enter the system date and time every time the computer was started. Now it's essentially included as a way to set the data from the command line; the preferred method is to use Control Panel Date and Time.
If you type time on the command line without an option, the current time setting is displayed, and you are prompted for a new one. Press Enter to keep the same date.
The time options are:
Sets the system time without a prompt. The format of time is hh : mm : ss [ A P ], where:
Hours: valid values = 0-23
Minutes: valid values = 0-59
Seconds: valid values = 0-59
A.M. or P.M. (for a 12-hour format). If a valid 12- hour format is entered without an A or P, A is the default.
Displays the current time without prompting for a new one.
The time format depends on settings in Control Panel Regional and Language Options.
Windows records the current time for each file you create or change. This time is listed next to the filename in the dir directory listing.
The time display format for most applications can be changed in Control Panel Regional and Language Options Regional Options tab Customize, but this doesn't affect the output of the DOS time command.
To have Windows automatically synchronize the clock with an Internet time server, go to Control Panel Date and Time Internet Time tab.
"time"
type |
Display the contents of a text file.
type filename
The type command is useful if you need to quickly view the contents of any text file ( especially short files). type is also useful for concatenating text files, using the >> operator.
If the file is exceptionally long, you can press Ctrl-C to interrupt the display before it's finished.
"more", "echo"
ver |
Display Windows version information.
ver
ver shows the version of Windows you're using. You can also find the Windows version at Control Panel System General tab, but it won't show you the revision number.
ver takes no options.
This undocumented option also displays the revision number, and whether DOS is located in the high memory area (HMA; the same as DOS=HIGH).
Windows XP is known internally as Windows NT 5.1. xxxx , where xxxx is the build/revision number.
"Windows Update" in Chapter 4
xcopy | \windows\system32\xcopy.exe |
Copy files and directory trees (directories, subdirectories, and their contents).
xcopy source [ destination ] [/a /m] [/d[: date ]] [/p] [/s [/e]]
[/v] [/w] [/c] [/i] [/q] [/f] [/l] [/g] [/h] [/r] [/t] [/u]
[/k] [/n] [/o] [/x] [/y] [/-y] [/z] [/exclude: filenames ]
xcopy works like copy , but provides more options and is often faster.
The xcopy32 options are:
Specifies the file(s) to copy; source must include the full path.
Specifies the location and/or name of new files. If omitted, files are copied to the current directory.
Copies files with the archive attribute set, but doesn't change the attribute of the source file (similar to /m ).
Continues copying even if errors occur.
Copies only files changed on or after the specified date. If no date is given, copies only those source files that are newer than existing destination files.
Copies all directories and subdirectories (everything), including empty ones (similar to /s .) May be used to modify /t .
Specifies a file (or a list of files) containing strings of text (each on its own line). When any of the strings match any part of the absolute path of the file to be copied, that file will be excluded from being copied. Contrary to what you might expect, filenames does not actually list the filenames to exclude.
Displays full source and destination filenames while copying (unless /q is specified); normally, only filenames are displayed.
Allows the copying of encrypted files to a destination that does not support encryption; otherwise, such files are skipped.
Copies hidden and system files also; normally files with the hidden or system attributes are skipped (see "Attrib" in Chapter 4 for details).
If a destination is not supplied and you are copying more than one file, assumes that the destination must be a directory. (By default, xcopy asks if the destination is a file or directory.)
Duplicates the attributes of the source files; by default, xcopy turns off the read-only attributes (see "Attrib" in Chapter 4 for details).
Displays files that would be copied given other options, but does not actually copy the files.
Copies files with the archive attribute set, then turns off the archive attribute of the source file (similar to /a ).
Copies files using short (8.3) file and directory names (for example, PROGRA~1 instead of Program Files ). Use this feature to convert an entire branch of files and folders to their short names.
Copies file ownership and ACL information.
Prompts you before creating each destination file.
Quiet mode; does not display filenames while copying.
Overwrites read-only files.
Copies directories and subdirectories, except empty ones (similar to /e .)
Creates the directory structure, but does not copy files; does not include empty directories unless /e is specified.
Copies from the source-only files that already exist on destination; used to update files.
Verifies copied files by comparing them to the originals.
Prompts you to press a key before copying (useful in batch files).
Copies file audit settings (implies /o ).
Turns off or on (respectively) the prompt for overwrites existing files.
Copies networked files in restartable mode.
The following are exit codes generated by xcopy , and can be tested in batch file with ERRORLEVEL to determine if the xcopy operation was successful:
All files were copied without errors.
No files were found to copy.
xcopy was terminated by Ctrl-C before copying was complete.
An initialization error occurred. Such an error would generally be caused by insufficient memory or disk space, or an invalid drive name or syntax.
A disk-write error occurred.
Copy all the files and subdirectories, including any empty subdirectories and hidden files, from c:\foobar to the root directory of d:
C:\> xcopy \foobar d: /s /e /h
copy , move , and xcopy will prompt you before overwriting an existing file, unless you specify a command line parameter instructing them to do otherwise. To change the default, set the copycmd environment variable to /y . To restore the default behavior, set copycmd to /-y . See "set" for details.
In some earlier versions of Windows, there were to versions of xcopy : xcopy.exe and xcopy32.exe . In Windows XP, the xcopy command is equivalent to the 32-bit xcopy32.exe utility; there's no equivalent to the old 16-bit xcopy.exe , however.
Use caution when using the /s or /e options in conjunction with /d or /u , as the results may be unpredictable.
"copy"