In addition to the various command-line parameters used by each of the commands documented in this chapter (and the components documented in other places in this book), certain symbols used on the command line have special meaning. Table 14-1 shows these special symbols and what they do. You must use them in conjunction with other commands (they don’t stand alone), and you can use them in the Command Prompt window, in Start → Run, and in an Address Bar.
Table 14-1. Special symbols on the command line
Symbol |
Description |
---|---|
* |
Multiple-character wildcard, used to specify a group of files. |
? |
Single-character wildcard, used to specify multiple files with more precision than *. |
. |
One dot represents the current directory; see "cd or chdir,” later in this chapter. |
.. |
Two dots represent the parent directory; see "cd or chdir,” later in this chapter. |
Separates directory names, drive letters, and filenames. By itself, represents the root directory of the current drive. | |
\ |
Indicates a network location, such as |
> |
Redirects a command’s text output into a file instead of the Console window; if that file exists, it will be overwritten. |
>> |
Appends a command’s text output to the end of a file instead of the Console window. |
< |
Directs the contents of a text file to a command’s input; use with filter programs (such as |
| |
Redirects the output of a program or command to a second program or command (this is called a pipe). |
For information about special operators for chaining commands and redirection, see http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx and http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx.
The following examples demonstrate some uses of wildcards, pipes, and redirection:
*.*
Specify all files with all extensions.
professor*.*
Specify all files (with filenames that begin with professor) with any extension.
chap??.doc
Specify all files named chap followed by any two characters and with the doc extension (e.g., chap01.doc, but not chap1.doc or chap.doc).
dir ..
List all the files in the current directory’s parent.
dir > c:
utshellmylist.txt
List all files in the current directory and store this listing into a file called mylist.txt rather than displaying it in the Command Prompt window. If the file already exists, it will be overwritten.
In addition to directing output to a file, you can direct to a device, such as NUL (an electronic void). This is useful if you want a command to run without sending output to the screen. Other special device names include CON (the console input/output stream), LPTx (the parallel printer port, where x is from 1 to the number of ports you have), and COMx (serial ports, including Bluetooth and USB/serial ports, where x corresponds to the numbers shown in Device Manager).
dir c:windows >> c:
utshellmylist.txt
Add the directory listing of the files in the c:Windows directory to the end of the file windows.txt.
If the specified file doesn’t exist, one is created. If one does exist, the output from the command is added to it, unlike with the >
key, where the original contents are overwritten.
echo y | del *.*
Normally, the DEL
command has no prompt. However, if you try to delete all the files in a directory, del
will prompt you for confirmation. To automate this command, the output of the ECHO
command (here, just a “y” plus a carriage return) is “piped” into the input (commonly known as STDIN, or standard input) of the DEL
command.
del *.* < y.txt
Assuming y.txt contains only a letter y followed by a carriage return, this command has the same effect as the preceding example.
sort /+12 < c:
utshellmylist.txt
To sort the lines in a text file (c:
utshellmylist.txt) on the 12th character, the SORT
command is fed input from the file. The output is sent to the screen, not reordered in the file.
Keep in mind that not all commands handle wildcards in exactly the same way. For example, dir *
and dir *.*
list the same thing.
Most of the following commands are not standalone applications, 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.
Note that before listing each individual command, I’m first offering more details on how to use the Command Prompt. Here is an alphabetical reference of entries in this chapter:
Attrib |
find |
rem |
call |
for |
ren or rename |
cd or chdir |
goto |
robocopy |
Choice |
if |
set |
clip |
md or mkdir |
shift |
cls |
mklink |
sort |
Command Prompt |
more |
time |
copy |
move |
timeout |
date |
Path |
type |
del or erase |
pause |
ver |
dir |
prompt |
where |
echo |
query |
whoami |
errorlevel |
quser |
xcopy |
exit |
rd or rmdir |
Command Prompt: windowssystem32cmd.exe
The Windows Vista command-line interface, commonly referred to as a DOS box or Command Prompt.
To open
Start → All Programs → Accessories → Command Prompt
Command Prompt → cmd
Usage
cmd [/q][/d] [/a|/u] [/e:on|off][/f:on|off][/v:on|off] /t:fg
[[/s][/c|/k]string
]
Description
As explained earlier in this chapter, the Command Prompt (see Figure 14-5) is a simple application in which you type commands rather than pointing and clicking. Although the Command Prompt is sparse and may be somewhat intimidating to new users, it carries out several very important functions in Windows Vista, including access to otherwise inaccessible programs and utilities and even some advanced file management functions.
Figure 14-5. Using the DIR command to view the contents of the current directory in the Command Prompt
Cmd
accepts the following parameters:
string
When used with /c
or /k
, specifies a command to be carried out when the Command Prompt window is first opened. You can specify multiple commands here if you separate them with &&
, and string
, as a whole, is surrounded by quotation marks. String
must be the last parameter on the command line.
/c
Carries out the command specified by string
and then stops.
/k
Carries out the command specified by string
and continues.
/s
Strips any quotation marks in string
. Type cmd /?
for details.
/q
Turns the echo off; see "echo,” later in this chapter.
/d
Disables execution of AutoRun
commands. Without /d
, any programs or commands listed in the Registry keys, HKEY_LOCAL_MACHINESoftwareMicrosoftCommand ProcessorAutoRun
and HKEY_CURRENT_USERSoftwareMicrosoftCommand ProcessorAutoRun
, are executed every time a Command Prompt window is opened.
/a
Formats all Command Prompt output so that it is American National Standards Institute (ANSI)-compliant.
/u
Formats all Command Prompt output so that it is Unicode-compliant.
/e:on|off
Enables or disables command extensions (the default is on). Turn off command extensions to disable certain advanced features of the commands discussed in this chapter.
/f:on|off
Enables or disables file and directory name completion (the default is off). Type cmd /?
for details.
/v:on|off
Enables or disables delayed environment variable expansion (the default is off). Type cmd /?
for details.
/t:
fg
Sets the foreground and background colors (f
and g
, respectively) of the Command Prompt window. The single-digit values for f
and g
are as follows: 0
= Black, 1
= Blue, 2
= Green, 3
= Aqua, 4
= Red, 5
= Purple, 6
= Yellow, 7
= White, 8
= Gray, 9
= Light blue, A
= Light green, B
= Light aqua, C
= Light red, D
= Light purple, E
= Light yellow, and F
= Bright white.
Notes
Also included with Windows Vista is command.com, the command prompt used in Windows 9x/Me. It’s used similarly to cmd.exe but has limited support of long filenames and other Windows Vista features. Command.com is included for legacy purposes only and should be avoided; cmd.exe is the preferred command prompt in Windows Vista.
If you need to play an old DOS game, take a look at DOSBox (http://dosbox.sourceforge.net), which not only emulates DOS well, but also supports sound in older games.
Attrib: windowssystem32attrib.exe
Change or view the attributes of one or more files or folders.
To open
Command Prompt → attrib
Usage
attrib [+r|-r] [+a|-a] [+s|-s] [+h|-h] [filename] [/s [/d]]
Description
Attrib allows you to change the file and folder attributes from the command line—settings otherwise available only in the Properties window of a file or folder. You can think of the attributes as switches, independently turned on or off for any file or group of files. The individual attributes are as follows:
R
(read-only)
Turn on the read-only attribute of a file or folder to protect it from accidental deletion or modification. If you attempt to delete a read-only file, Windows will prompt you before allowing you to delete it. Different applications handle read-only files in different ways; usually you will not be allowed to save your changes to the same filename.
A
(archive)
The archive attribute has no effect on how a file is used, but it is automatically turned on when a file is modified or created. It is used primarily by backup software to determine which files have changed since a backup was last performed; most backup programs turn off the archive attribute on each file that is backed up.
S
(system)
Files with the system attribute are typically used to boot the computer. There’s little reason to modify a file with the system attribute, or to ever turn on or off the system attribute for any file. If you turn off the system attribute of an important file, it may stop the file from working. See “Notes,” later in this section, for information on displaying or hiding system files.
H
(hidden)
To hide any file or folder from plain view in Explorer or on the Desktop, turn on its hidden attribute. See “Notes,” later in this section, for more information.
Examples
To hide a file in Explorer, right-click on it, select Properties, and turn on the hidden option. To hide the same file using the command line, type:
attrib +h filename
where filename
is the full path- and filename of the file to change. To specify multiple files, include a wildcard, such as *.*
(for all files) or *.txt
(for all files with the .txt filename extension). Note the use of the plus sign (+) to turn on an attribute; use the minus sign (-) to turn it off. For example, to turn off the hidden attribute and simultaneously turn on the archive attribute, type:
attrib -h +a filename
To display the attributes of a file or a group of files in Explorer, select Details from the View menu. Then, select Choose Details from the View menu and turn on the Attributes option. To display the attributes of a file or a group of files on the command line, type:
attrib filename
where filename
is the full path- and filename(s) of the files you want to view. Omit filename
to display the attributes of all the files in the current folder. If filename
is not used, or if it contains wildcards (in other words, if the command is intended to act on more than one file), you can use the /s
option to further include the contents of all subfolders of the current folder. The /d
option instructs Attrib to act upon folders as well as files, but it has meaning only if you use it in conjunction with the /s
parameter.
Notes
By default, files with the system or hidden attributes are not shown in Explorer. To display system and hidden files, go to Explorer → Organize → Folder and Search Options → View and select “Show hidden files and folders.”
Attrib does not let you change the Advanced attributes, such as those concerned with indexing, compression, or encryption.
cd or chdir
Display the name of, or change, the current working directory (folder).
Usage
cd [/d] [directory
] chdir [/d] [directory
]
Description
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:
ightmare
), 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 following examples).
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 path .. refers to the parent of the current directory.
Examples
If the current drive is C:, make c: empwild the current directory:
C:>cd empwild
C: empwild>
Note how the current working directory is displayed in the prompt. If the current directory is c: emp, all that is necessary is:
C: emp>cd wild
C: empwild>
Change to the parent directory:
C:moredocsmisc>cd ..
C:moredocs>
Change to the root directory of the current drive:
C:WindowsDesktop>cd
C:>
Change to another drive:
C:>cd /d d:
D:>
or simply:
C:>d:
D:>
Notes
The chdir
and cd
commands are functionally identical.
The “current working directory” has meaning only 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 its default (usually your home directory, but you can set it 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.
clip
Redirects the output of command-line tools to the Windows Clipboard, where the text can then be pasted into another program.
Usage
[Command] | clip clip < [filename.txt]
Description
clip
is extremely useful for when you want to capture output from a command on the command line so that you can paste it into an application. A simple use would be to print out the listing of a directory: use the dir
command along with clip
and then paste the output from the Clipboard into a text editor, where you can print it. Note that when you use the command, the output is suppressed in the command box. So, for example, when you type dir | clip
, the directory listing will not be displayed but will be placed into the Clipboard. You can also use clip
to copy the entire text from a text file to the Clipboard. You can’t, however, use it to copy the contents of other kinds, such as .doc files.
Examples
Copy information about currently logged-on users to the Clipboard:
quser | clip
Copy the text of the file newinfo.txt to the Clipboard. Note that the file has to be in your current directory:
clip < newinfo.txt
Notes
clip
is new to Windows Vista.
cls
Clear the Command Prompt window and buffer, leaving only the Command Prompt and cursor.
Description
Type cls
at the prompt to clear the screen and the screen buffer (see "Using the Command Line,” 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 files—for 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.
Usage
copysource destination
copy [/a | /b]source
[/a | /b] [+source
[/a | /b] [+ ...]] [destination
[/a | /b]] [/v] [/y | /-y] [/d] [/z] [/n] [/l]
Description
copy
makes a complete copy of an existing file. If another file by the same name exists at destination
, you will be asked whether 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:
/a
Specifies that the file to copy is in ASCII format.
/b
Specifies that the file to copy is a binary file.
/v
Verifies that new files are written successfully by comparing them with the originals.
/y
Suppresses prompting to confirm that you want to overwrite an existing destination file.
/-y
Enables prompting to confirm that you want to overwrite an existing destination file with the same name (default).
/d
Allows the new file to be created as a decrypted file (NTFS volumes only).
/l
When copying a symbolic link (see "mklink,” later in this chapter), copies the file as a link rather than making a couple of the source file (the default behavior).
/n
Copies the file using the short filename that Vista generated for compatibility with DOS, old versions of Windows, and devices that can’t support long filenames on their flash memory.
/z
Copies networked files in restartable mode. If the network connection is lost during copying (if the server goes offline and severs the connection, for example), /z
will resume the copying after the connection is reestablished.
Examples
Copy the file temp.txt from C: to d:files (all three examples do the same thing):
C:>copy c: emp.txt d:files emp.txt
C:>copy c: emp.txt d:files
C:>copy temp.txt d:files
The third sample in the preceding code works here because the source file is located in the current directory. Here’s another way to do it:
C:>d:
D:>cd files
D:files>copy c: emp.txt
Copy all the files from the directory d:CdsampleImages to the current directory, giving the copies the same names as the originals:
C:>copy d:cdsampleimages*.*
C:>copy d:cdsampleimages*.*
.
Copy the file words.txt in the current directory to d:files, renaming it morewords.txt:
C:>copy words.txt d:filesmorewords.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
Notes
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 Universal Naming Convention [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).
You also can use the con
device (console) 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,” later in this chapter):
C:>copy mystuff.txt con
Binary file copying is assumed for normal copying, but you should use the /b
option when appending one binary file to another, as in:
C:>copy file1+file2 newfile /b
By default, when concatenating, both the source and destination files are assumed to be ASCII format, because 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 0 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,” later in this chapter, for details.
date
Display or set the system date.
Usage
date [/t | date
]
Description
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 date from the command line; the preferred method is to use Control Panel → [Clock, Language and Region] → 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:
date
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 8907. Separate month, day, and year with periods, hyphens, or slashes.
/t
Displays the current date without prompting for a new one. You can use this if you need to append a timestamp to the end of a file, as in date /t >> logfile.txt
.
Notes
The date format depends on settings in Control Panel → [Clock, Language, and Region] → 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.
You can change the date display format for most applications in Control Panel → [Clock, Language, and Region] → Change the date, time, or number format → Customize this format, but this doesn’t affect the output of the DOS date
command.
See also
"time"
del or erase
Usage
del [/p] [/f] [/s] [/q] [/a:attributes
]filename
erase [/p] [/f] [/s] [/q] [/a:attributes
]filename
Description
You use the del
command to delete one or more files from the command line without sending them to the Recycle Bin.
The del
options are:
filename
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.
/p
/f
Forces deletion of read-only files.
/s
Deletes specified files in all subdirectories (when using wildcards).
/q
Quiet mode; do not prompt if filename
is *.*
.
/a:
attributes
Selects files to delete based on attributes (read-only, hidden, system, or archive). See "Attrib,” earlier in this chapter, for more information on attributes.
Examples
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:filesmyfile.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:filesmyfile.* /p
Notes
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).
Usage
dir [filename
] [/b] [/c] [/d] [/l] [/n] [/p] [/q] [/s] [/w] [/x] [/4] [/a:attributes
] [/o:sortorder
] [/t:timefield
]
Description
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.
You can use wildcards (*
and ?
) to display a subset of files and subdirectories in a given location.
dir
accepts the following options:
/a:
attributes
Displays only files with/without specified attributes (using -
as a prefix specifies “not,” and a colon between the option and attribute is optional). See "Attrib,” earlier in this chapter, for more information on attributes.
/b
Use bare format (no heading information or summary). Use with /s
to list all files in the current directory and subdirectories.
/c
Displays the thousand separator in file sizes. This is the default; use /-c
to disable display of the separator.
/d
Same as /w
, except files are sorted vertically.
/l
Use lowercase.
/n
Lists files in a Unix-like display, where filenames are shown on the right. This is the default view.
/o:
sortorder
Lists files in sorted order (using -
as a prefix reverses the order, and a colon between the option and attribute is optional):
d
By date and time (earliest first)
e
By extension (sorted alphabetically)
g
Group directories first
n
By name (sorted alphabetically)
s
By size (smallest first)
/p
Pauses after each screenful of information; press any key to continue.
/q
Displays the owner of each file.
/s
Includes all files in all subdirectories, in addition to those in the current directory.
/t:
timefield
Controls which time is used when sorting:
c
Created
a
Last accessed
w
Last modified (written)
/w
Wide list format. File- and directory names are listed in columns and sorted horizontally. The actual number of columns varies based on the length of the longest filename and the screen width. Use /d
instead to sort vertically.
/x
Include the “short” 8.3 versions of long filenames. For example, Sam’s File.txt has an alternate filename, samsfi~1.txt, to maintain compatibility with older applications.
/4
Display the listed years as four digits. By default, two-digit years are displayed.
Examples
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 \bubbacdrom
Notes
To change the default sort order, set the dircmd
environment variable to the same value you’d use with the /o
parameter. See "set,” later in this chapter, 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 > filename
C:>notepad /p filename
To create a file containing the directory listing of the same directory:
C:>dir c:windows /oa > c:myfileswindows.txt
Files and folders that are hidden (see "Attrib,” earlier in this chapter) will not show up in dir
listings by default. However, if you know the name of a hidden directory, nothing is stopping you from displaying a listing of the contents in that directory. You can also use dir /a
.
echo
Display a string of text; turn command echoing on or off.
Usage
echo [on | off | message
]
Description
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.
You can use the following options with echo
:
on | off
By default, each command in a batch file is echoed to the screen as it is executed; echo on
and echo off
toggle 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.
message
Types the message you’d like displayed to the console (screen).
Examples
To display an ordinary message, use the following:
echo Hello World!
To display a blank line, use one of the following (both are equivalent):
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 emp directory from a batch file, you could use the following command:
echo y | del c: emp*.*
or even:
echo y | if exists c: emp*.* del c: emp*.*
This construct works because the pipe character takes the output of the first command and inserts it as the input to the second.
You can use echo
to 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 users 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 . . . goto end :usage echo You must supply a filename. :end
See also
"type"
exit
End the current Command Prompt session and close the window.
Usage
exit [/b] [exitcode
]
Description
Typing exit
has the same effect as closing the Command Prompt window with the [x] button.
exit
accepts the following options:
/b
If you use exit
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.
exitcode
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 it was successful.
Notes
If you start a new Command Prompt session by typing cmd
in an open Command Prompt window, exit
will end that session. However, because the “parent” session is still active, the window won’t close until you type exit
again.
find: WindowsSystem32find.exe
Search in one or more files for text.
Usage
find [/v] [/c] [/n] [/i] [/offline] "string
" [filename
[ ...]]
Description
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.
The find
options are:
"string"
The text to look for, enclosed in quotation marks.
filename
The file(s) in which to search. Wildcards (*
, ?
) are supported, and you can specify multiple filenames as long as you separate them 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 "Wildcards, Pipes, and Redirection,” earlier in this chapter.
/c
Displays only the count of lines containing the string.
/i
Ignores the case of characters when searching for the string.
/n
Displays line numbers with the displayed lines.
/v
Displays all lines not containing the specified string.
/offline
Includes files with the offline attribute set (that otherwise would be skipped).
Examples
Search for redflag in myemployees.txt:
C:>find "redflag" myemployees.txt
Count occurrences of the word deceased in myemployees.txt:
C:>find /c "deceased" myemployees.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
Notes
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 this:
dir c: /s /b | find "chap"
to search the contents of all files for the string "chap"
, but in fact, all you’d be doing is running find
on the list of filenames, not on their contents. You can accomplish this with the new forfiles
command:
forfiles /p C: /s /c "cmd /c find "chap" @path"
find
won’t recognize a string that has a carriage return embedded in it. For example, if “chapter” is at the end of one line and “05” on the next, find
won’t report a match on “chapter 05.”
A similar command, findstr
, offers even more ways to find strings of text in files. For example, you can match patterns only if they’re at the beginning or the end of a line, among other capabilities. For details, type findstr /?
at a command prompt.
md or mkdir
Create a new directory (folder).
Usage
md [drive
:]path
mkdir [drive
:]path
Description
Windows Vista, 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:
[drive:]path
Specifies the directory to create.
Examples
Create a subdirectory named harry in the current directory:
C: omdick>md harry
Create a new directory called newdir under the c:olddir directory:
C:>md c:olddir
ewdir
If c:olddir doesn’t exist, it will be created as well.
Create two new directories, c: olling and c:stones:
C:>md rolling stones
Create a single new directory, c: olling stones:
C:>md "rolling stones"
(Enclose directory names in quotation marks to accommodate spaces.)
Notes
The md
and mkdir
commands are functionally identical.
You can also create new folders in Windows Explorer by going to Organize → 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.
mklink
Create a link to another file or directory
Usage
mklink [/d] | [/h] | [/j]] link target
Description
mklink
is used to create a Unix-style link to another file or directory; that link can be used just as if it were the original file or directory. When you create a symbolic link to a file, that file will show up in Windows Explorer as a shortcut, and if you use the command line to get a directory listing, it will be listed as a <SYMLINK>
instead of as <DIR>
, and you’ll see the symbolic link followed by the real file. For example, if you create a symbolic link called newone to the file test, here’s what you would see:
<SYMLINK> newone [c: est]
The mklink
options are:
/d
Creates a symbolic link (the default). Use /j
for directories.
/h
Creates a hard link instead of a symbolic link. You will not see SYMLINK
in the dir listing, because a hard link is a first-class filename. Creating a hard link to an existing file adds another filename, and the file is not deleted until you delete the last hard link to it.
/j
Creates a directory junction. You will see JUNCTION
in the dir listing instead of SYMLINK
.
link
Specifies the new symbolic link name.
target
Specifies the path (relative or absolute) that the new link refers to.
Notes
mklink
is new in Windows Vista. It has to be run from an administrator prompt (locate Command Prompt in the Start menu, right-click on it, and select Run as Administrator).
The difference between symbolic and hard links is subtle. If you delete the target of a soft link, the soft link remains, but it is invalid until you re-create the target. If you delete the target of a hard link, the hard link is still valid because it’s essentially an additional filename by which the file is referenced.
more: windowssystem32more.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.
Usage
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]]
Description
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:
filename
Specifies the name of a file to display.
/c
Clears the screen before displaying the file.
/e
If the /e
option is specified, the following additional extended commands are available at the -- More --
prompt:
P
n
Displays next n
lines
S
n
Skips next n
lines
Spacebar
Displays next page
Enter
Displays next line
F
Displays next file
Q
Quits
=
Shows line number
?
Shows help
/p
Expands form-feed characters.
/s
Squeezes multiple blank lines into a single line.
/t
n
Expands tabs characters to n
spaces (default 8).
+
n
Starts display of the file at line n
.
filename
Specifies the name of a file to display.
Examples
Display the contents of Windows eadme.txt and pause for each screenful of text (both of the following examples have the same effect):
C:>more c:windows eadme.txt
C:>type c:windows eadme.txt | more
Keep the output of dir
from scrolling off the screen before you can read it:
C:>dir c:windows | more
Notes
Some commands (such as dir
) have a /p
option that “pages” the output (e.g., dir | more
is the same as dir /p
), but many do not.
See also
"type"
move
Move files and directories from one location to another.
Usage
move [/y | /-y]filename
[,...]destination
Description
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 by commas), or a single file specification with wildcards.
The move
options are:
filename
Specify the location and name(s) of the file or files you want to move. Wildcards (*
, ?
) are supported.
destination
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. If you include the new filename but omit the drive or directory name, move
effectively renames the file.
/y
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.
/-y
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.
Examples
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
ewfile.txt
Change the name of the directory d:files to d:myfiles:
D:>move d:files myfiles
Notes
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,” later in this chapter, for details.
See also
path
Set or display the command search path.
Usage
path [path1
][;path
2][;path
3][;...]
Description
When you type an executable filename at the Command Prompt (as opposed to a command built into the Command Prompt), 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 folders, which 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 current directory’s drive.
Type path
without any arguments to display the current command search path. The default path in Windows Vista is c:windowssystem32;c:windows;c:windowssystem32wbem
.
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, .cmd. 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).
Examples
Specify the directories c:Stuff and d:Tools in the path:
C:>path c:stuff;d: ools
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: ools
Notes
The path is actually an environment variable and the path
command is merely a shortcut for the following:
set path=%path%;c:stuff;d: ools
See "set,” later in this chapter, for more information on environment variables and details on setting global environment variables that don’t expire when the Command Prompt window is closed.
Windows Vista 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 your current Command Prompt to search only in the current directory.
The order of directories in the search path is quite important. For example, you might run Cygwin (http://www.cygwin.com), a free set of open source tools that brings Unix functionality to Windows systems. Cygwin normally stores its files in cygwinin, but if you have the path set as follows:
path=C:cygwinin;C:Windowssystem32;C:Windows;C:Windowssystem32wbem
you won’t be able to run a Windows command such as find
without typing its full pathname because the Cygwin find
command will be found and executed first. To avoid this problem, put C:cygwinin at the end of your PATH
.
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.
Usage
prompt [text
]
Description
Type prompt
by itself (without text
) to reset the prompt to its default setting.
The prompt
options are:
text
Specifies a new command prompt. text
can contain normal characters and the following special codes:
$_
Carriage return and linefeed
$$
Dollar sign ($
)
$a
Ampersand (&
)
$b
Pipe (|
)
$c
Left parenthesis ((
)
$d
Current date
$e
Escape character (ASCII code 27), used to provide extended formatting
$f
Right parenthesis ()
)
$g
Greater-than sign (>
), commonly known as the caret
$h
Backspace (erases preceding character)
$l
Less-than sign (<
)
$n
Current drive
$p
Current drive and path
$q
Equals sign (=
)
$s
Space
$t
Current time
$v
Windows version number
Examples
Specify the current drive and directory followed by the greater-than sign (>
), the default prompt in Windows Vista:
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
Notes
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 on environment variables and details on setting global environment variables that don’t expire when the Command Prompt window is closed.
query
Find out information about sessions, processes, and users.
Usage
query process | session | termserver | user
Description
The query
options are:
process
Lists the currently running processes, including filenames, and associated usernames
session
Lists the current sessions, including their IDs and associated usernames
termserver
Lists the currently running terminal servers
user
Lists information about logged-in users, including the time they logged on, their amount of idle time, their session name, and their session ID
quser
Displays information about users currently logged on to the system. (Not available in the Home edition.)
Usage
quser username sessionname sessionid
Description
quser
displays information about currently logged-on users. It displays when the user logged on, whether the user is active, and the current time, the username, the session name, the session ID, and the amount of idle time for the user. (To find the session ID, use the query
command. See the preceding section, "query.”) You can use the following commands with quser
:
username
Identifies the username of the user for whom you want to display information
sessionname
Displays the session name (for example, console
) of the user for whom you want to display information
sessionid
Displays the session ID (for example, 2
) of the user for whom you want to display information
Examples
Display information about the user preston
:
quser preston
Display information about the user with the session name console
:
quser console
Notes
quser
is new to Windows Vista.
rd or rmdir
Usage
rd [/s] [/q]path
rmdir [/s] [/q]path
Description
Unlike in Windows Explorer, files and folders are deleted differently; if you try to use del
to delete a directory, it will simply delete all the files in the directory, but the directory itself will remain. You use rd
to delete empty directories and, optionally, to delete directories and all of their contents.
rd
accepts the following options:
path
Specifies the directory to delete.
/s
Removes all files and subdirectories of the specified directory.
/q
Quiet mode; don’t prompt when using /s
.
Examples
Delete the empty subdirectory called newdir located in the c:olddir directory:
C:>rd c:olddir
ewdir
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 you must use quotes with rd
for folders with spaces in their names.
Notes
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 Vista.
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
Usage
ren [filename1
] [filename2
] rename [filename1
] [filename2
]
Description
Use ren
to rename any file or directory. Unlike in Windows Explorer, though, ren
is capable of renaming
several files at once (via the wildcards *
and ?
).
The ren
options are:
[
filename1
]
The name of the existing file or directory
[
filename2
]
The new name to assign to the file or directory
Examples
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 represents 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 space problem. Here, both chap 5.doc and sect 5.doc have spaces in the fifth character position, so you can use the single wildcard character (?
).
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
Notes
The ren
and rename
commands are functionally identical.
You can’t move files from one directory to another with ren
; use move
instead.
The file’s Last Modified date is not changed when you use ren
.
See also
"move"
robocopy
A powerful, flexible tool for copying files.
Usage
robocopy source [drive:path or \serversharepath] destination [drive:path or \serversharepath] [file [file]...] /a /m /s /e /mov /move /lev:n /fat
Description
robocopy
stands for Robust Copy for Windows, and the name is apt. It is far more powerful than the copy
and xcopy
commands, and in fact, a full explication of all of its commands and uses would take up half this chapter. For details about its full usage, type robocopy /?
to get help.
You can use the command to copy files not only on a PC, but also between PCs and servers, and between servers as well. It can use wildcards for file selection.
The following are some of the primary commands that you can use with robocopy
:
/a
Copy only files with the Archive
attribute set.
/m
Copy only files with the Archive
attribute and reset it.
/s
Copy subdirectories, but not empty ones.
/e
Copy subdirectories, including empty ones.
/mov
Move files (delete from source after copying).
/move
Move files and directories (delete from source after copying).
/lev:
n
Copy on the top n levels of the source directory tree.
/fat
Create destination files using 8.3 FAT filenames only.
/mir
Mirrors a complete directory tree. You also can use it with other commands, such as /b
for copying files in backup mode, to copy only files that have been changed.
Examples
Copy all .xls files from C: ewbudget to F: ewbudget, and use only 8.3 FAT filenames:
robocopy *.xls c: ewbudget f: ewbudget /fat
Notes
robocopy
is new to Windows Vista.
See also
“copy” and “xcopy”
set
Display, assign, or remove environment variables.
Usage
set [variable
[=[string
]]] set /pvariable
=[promptstring
] set /aexpression
Description
The environment is a small portion of memory devoted to the storage of a few values called environment variables. You use set
to manipulate environment variables from the command line, but because the Command Prompt’s environment is reset when its window is closed, the usefulness of set
is fairly limited for interactive use, although you’ll use it a lot in your own batch files.
To make more permanent changes to environment variables, go to Control Panel → [System and Maintenance] → System → Advanced system settings → Environment variables. The variables in the upper listing are for the current user and the 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%AppDataLocalTemp
where %USERPROFILE%
(note the percent signs [%
] on both sides) 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 "Batch Files,” later in this chapter).
Type set
without options to display all of the current environment variables. Type set
with only a variable name (no equals sign or value) to display a list of all the variables whose prefix matches the name.
The set
options are:
variable
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 equals sign, the variable is assigned an empty value and deleted. Variable
cannot contain the equals sign (=
).
string
Specifies a series of characters to assign to variable
. As stated earlier, this can contain references to other variables when surrounded with preceding and trailing percent signs (%
).
/p
Specifies that variable
will be assigned by text input from the user, rather than string
. As stated earlier, this can contain references to other variables with preceding and trailing percent signs (%
).
promptstring
The text prompt to display when using the /p
option.
/a
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.
expression
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):
( )
Parentheses for grouping
! ~ -
Unary operators (not, bitwise not, negative)
*/ %
Arithmetic operators (multiply, divide, modulus)
+−
Arithmetic operators (add, subtract)
<< >>
Logical shift
&
Bitwise “and”
^
Bitwise “exclusive or”
|
Bitwise “or”
= *= /= %= += −= &= ^= |= <<= >>=
Assignment
'
Expression separator
If you use /a
with any of the bitwise 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.
Examples
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 equals 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 im'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. This is typically used in batch files (note that you have to put quotes around it, otherwise the >
will be interpreted as the redirection operator):
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 variable, 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 a 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 Vista recognizes the following variables (many of which are predefined):
ALLUSERSPROFILE
The location of the All Users folder, usually c:UsersAll Users.
APPDATA
The location of the Application Data folder, usually c:Users\%USERNAME%AppDataRoaming.
COMMONPROGRAMFILES
The location of the Common Files folder, usually c:Program FilesCommon Files.
COMPUTERNAME
The network name of the computer, which you can set by going to Control Panel → [System and Maintenance] → See the name of this computer → Change settings.
COMSPEC
The location of the Command Prompt application executable, c:Windowssystem32cmd.exe by default.
COPYCMD
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
.
DIRCMD
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.
ERRORLEVEL
The return code of the last command run. A zero value (0
) indicates success; anything else indicates failure.
HOMEDRIVE
The drive letter of the drive containing the current user’s home directory, usually c:, used with HOMEPATH
.
HOMEPATH
Along with HOMEDRIVE
, the path of the current user’s home directory, which is usually Users\%USERNAME%.
LOGONSERVER
The name of the computer as seen by other computers on your network, usually the same as COMPUTERNAME
preceded by two backslashes.
NUMBER_OF_PROCESSORS
The number of processors currently installed. In a multiprocessor or multicore system, it can be two, four, or more.
OS
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.
PATH
The sequence of directories in which the command interpreter will look for commands to be interpreted. See "path,” earlier in this chapter.
PATHEXT
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, .WSH, and .MSC.
PROCESSOR_ARCHITECTURE
The type of processor; set to x86
for 32-bit Windows running on Intel-compatible processors (such as the Core 2 Duo or Athlon X2).
PROCESSOR_REVISION
A series of values the processor manufacturer uses to identify the processor.
PROGRAMFILES
The location of the Program Files folder, usually c:Program Files.
PROMPT
The format of the command-line prompt, usually $P$G
. See "prompt,” earlier in this chapter, for details.
SESSIONNAME
The name of the current Command Prompt session, usually Console
.
SYSTEMDRIVE
The drive letter of the drive containing Windows, usually C:.
SYSTEMROOT
The location of the Windows directory (or more specifically, the name of the folder in which the WindowsSystem32 folder can be found), usually c:windows.
TEMP
, TMP
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:Users\%USERNAME%AppDataLocalTemp (short name used to maintain compatibility with older DOS programs).
USERDOMAIN
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
.
USERNAME
The name of the current user.
USERPROFILE
The location of the current user’s home directory, which should be the same as HOMEDRIVE
plus HOMEPATH
, usually c:Users\%USERNAME%.
WINDIR
The location of the Windows directory, usually c:windows.
Notes
Among the standard environment variables listed earlier, some represent certain system folders (such as PROGRAMFILES
). These variables reflect only the corresponding settings in the Registry (and elsewhere); changing them will affect only what is reported to applications that use these variables; it won’t actually change where Windows looks for these folders.
sort: windowssystem32sort.exe
Sort text or the contents of text files in alphanumeric order.
Usage
sort [/r] [/+n] [/mkilobytes
] [/llocale
] [/recrecordbytes
] [/t [tempdir
]] [/ooutputfilename
] [filename]
Description
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 you can change this 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:
/r
Reverses the sort order; that is, it sorts Z to A and then 9 to 0.
/+
n
Sorts the file according to characters in column n
.
/m
kilobytes
Specifies the 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 up the operation using temporary files.
/l
locale
Overrides the system default locale (see Control Panel → Regional and Language Options). The “C” locale yields the fastest collating sequence, and in Windows Vista, it is the only choice.
/rec
recordbytes
Specifies the maximum number of characters on a line (in a record); the default is 4,096 and the maximum is 65,535.
/t
tempdir
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.
/o
outputfilename
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).
filename
The name (and optionally, full path) of the file to sort.
Examples
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 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
Notes
The input to sort
should be plain 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 multiple fixed columns.
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 Cygwin; http://www.cygwin.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.
Usage
time [/t | time
]
Description
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 → [Clock, Language, and Region] → 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:
time
Sets the system time without a prompt. The format of time
is hh
:mm
:ss
[A
|P
], where:
hh
Hours: valid values = 0–23.
mm
Minutes: valid values = 0–59.
ss
Seconds: valid values = 0–59.
A|P
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.
/t
Displays the current time without prompting for a new one.
Notes
The time format depends on settings in Control Panel → [Clock, Language, and Region] → Date and Time.
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.
You can change the time display format for most applications in Control Panel → [Clock, Language, and Region] → Date and Time, but this doesn’t affect the output of the time
command.
To have Windows automatically synchronize the clock with an Internet time server, go to Control Panel → [Clock, Language, and Region] → Date and Time → Internet Time tab.
See also
"date"
type
Display the contents of a text file.
Usage
type filename
Description
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.
Notes
If the file is exceptionally long, you can press Ctrl-C to interrupt the display before it’s finished.
See also
“more” and "echo"
ver
Displays Windows version information.
Usage
ver
Description
ver
shows the version of Windows you’re using. You can also find the Windows version at Control Panel → [System and Maintenance] → System tab, but it won’t show you the revision number.
ver
takes no options.
Notes
See also
"Windows Update,” in Chapter 8
where
Displays the location of files that match a filename.
Usage
where /r /q [dir] /f /t [filename]
Description
where
will show you the location of files for which you’re searching. It searches along your default path, although you can add directories to the default with the use of /r
. It accepts wildcards such as *
and ?
. You can use the following commands with where
:
/r
Searches for and displays the file, starting with the specified directory
/q
Quiet mode (no output, but it sets the exit code in %ERRORLEVEL%
)
/f
Displays the matched filename in double quotes
/t
Displays the file size and last modified date and time for all matched files
Examples
Display the location of all files named eula.txt along the default path:
where eula.txt
Display the location and file size, and last modified date and time, for all .doc files in the directory latest:
where /r latest /t *.doc
Notes
where
is new to Windows Vista.
whoami
Gets username and group information, security identifiers (SIDs), privileges, and logon identifier (logon ID) for the current user.
Usage
whoami /upn /fqdn /user /groups /priv /logonid /all /fo format /nh
Description
You use whoami
to get a variety of information about the currently logged-in user. You can use the following options with the whoami
command:
/upn
Displays the username in User Principal Name (UPN) format. (Works only when the user is connected to a domain.)
/fqdn
Displays the username in Fully Qualified Distinguished Name (FQDN) format. (Works only when the user is connected to a domain.)
/user
Displays information about the current user along with the SID.
/groups
Displays group membership for the current user, the type of account, SIDs, and attributes.
/priv
Displays the security privileges of the current user.
/logonid
Displays the logon ID of the current user.
/all
Displays the current username and the groups the user belongs to, along with the SID and privileges for the current user.
/fo format
Specifies the output format to be displayed. Valid values are TABLE
, LIST
, and CSV
. Column headings are not displayed with the CSV
format. The default format is TABLE
.
/nh
Specifies that the column header should not be displayed in the output. This is valid only for the TABLE
and CSV
formats.
Examples
Display login ID and security privileges of the current user:
whoami /logonid
Display the current username, the groups the user belongs to, and the SID and privileges for the current user, in CSV
output format, with no header displayed:
whoami /all /fo CSV /nh
Notes
whoami
is new to Windows Vista.
whoami
is in essence the equivalent of the whoami
Unix command.
xcopy: windowssystem32xcopy.exe
Copy files and directory trees (directories, subdirectories, and their contents).
Usage
xcopysource
[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] [/b] [/exclude:filenames
]
Description
xcopy
works like copy
but provides more options and is often faster.
The xcopy32
options are:
source
Specifies the file(s) to copy; source
must include the full path.
destination
Specifies the location and/or name of new files. If omitted, files are copied to the current directory.
/a
Copies files with the archive attribute set but doesn’t change the attribute of the source file (similar to /m
).
/c
Continues copying even if errors occur.
/d
:date
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.
/e
Copies all directories and subdirectories (everything), including empty ones (similar to /s
). May be used to modify /t
.
/exclude:
filenames
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.
/f
Displays full source and destination filenames while copying (unless /q
is specified); normally, only filenames are displayed.
/g
Allows the copying of encrypted files to a destination that does not support encryption; otherwise, such files are skipped.
/h
Copies hidden and system files also; normally files with the hidden or system attributes are skipped (see "Attrib,” earlier in this chapter, for details).
/i
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.)
/k
Duplicates the attributes of the source files; by default, xcopy
turns off the read-only attributes (see "Attrib,” earlier in this chapter, for details).
/l
Displays files that would be copied given other options, but does not actually copy the files.
/m
Copies files with the archive attribute set, then turns off the archive attribute of the source file (similar to /a
).
/n
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.
/o
Copies file ownership and ACL information.
/p
Prompts you before creating each destination file.
/q
Quiet mode; does not display filenames while copying.
/r
Overwrites read-only files.
/s
Copies directories and subdirectories, except empty ones (similar to /e
).
/t
Creates the directory structure but does not copy files; does not include empty directories unless /e
is specified.
/u
Copies from the source-only files that already exist on destination; used to update files.
/v
Verifies copied files by comparing them to the originals.
/w
Prompts you to press a key before copying (useful in batch files).
/x
Copies file audit settings (implies /o
).
/y, /-y
Turns off or on (respectively) the prompt for overwriting existing files.
/z
Copies networked files in restartable mode.
/b
When copying a symbolic link (see "mklink,” earlier in this chapter), copies the file as a link rather than making a couple of the source file (the default behavior).
The following are exit codes generated by xcopy
. They can be tested in a batch file with ERRORLEVEL
to determine whether the xcopy
operation was successful.
0
All files were copied without errors.
1
No files were found to copy.
2
xcopy
was terminated by Ctrl-C before copying was complete.
4
An initialization error occurred. Such an error would generally be caused by insufficient memory or disk space, or an invalid drive name or syntax.
5
A disk-write error occurred.
Examples
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
Notes
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,” earlier in this chapter, for details.
In some earlier versions of Windows, there were two versions of xcopy
: xcopy.exe and xcopy32.exe. In Windows Vista, 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
option in conjunction with /d
or /u
, as the results may be unpredictable.
See also
“copy” and “robocopy”
18.191.195.111