CMD Computer Depth Programming
CMD Computer Depth Programming
Batch file commands
Control structures are mostly used inside batch files, although they can also
be used interactively.
:label
Defines a target for GOTO.
CALL
Executes another batch file and returns to the old one and continues.
FOR
Iteration: repeats a command for each out of a specified set of files.
GOTO
Moves execution to a specified label. Labels are specified at the beginning of a line, with a
colon (:likethis).
IF
Conditional statement, allows to branch the program execution.
PAUSE
Halts execution of the program and displays a message asking the user to press any key to
continue.
REM
comment: any text following this command is ignored.
SHIFT
Replaces each of the command-line variables with the consequent one (e.g. %0 with %1,
%1 with %2 etc.).
Variables
Batch files for COMMAND.COM can be said to have four kinds of variables:
1. ERRORLEVEL - contains the return code of the last program to run
that sets a value (an integer between 0 and 255). Most programs have a
certain convention for their return codes (for instance, 0 for a successful
execution). Some programs do not establish a new value, and thus the older
value persists after they execute. The value of ERRORLEVEL is tested for
range with the IF statement.
1. Environment variables - these have the form %VARIABLE% and are
associated with values with the SET statement. Most versions of
COMMAND.COM will only expand environment variables in batch mode.
2. Command-line parameters - these have the form %0, %1…%9, and
initially contain the command name and the first nine command line
parameters passed to the script (e.g., if the invoking command was
“myscript.bat John Doe”, then %0 is “myscript.bat”, %1 is “John” and %2 is
“Doe”). The parameters to the right of the ninth can be mapped into range by
using the SHIFT statement.
3. “For” variables - used by loops, have the format %%a when run in
batch files. These variables are defined solely within a specific FOR
statement, and iterate over a certain set of values defined in that FOR
statement.
Limitations
The command line length in interactive mode is limited to 126 characters. It
always returns a true value upon executing a command.
DOS
DOS (which is the abbreviation for “Disk Operating System”) is an acronym
for several closely related operating systems that dominated the IBM PC
compatible market between 1981 and 1995, or until about 2000 if one
includes the partially DOS-based Microsoft Windows versions 95, 98, and
Millennium Edition.
Related systems include MS-DOS, PC-DOS, DR-DOS, FreeDOS, PTS-DOS,
ROM-DOS, Novell DOS, OpenDOS, 86-DOS and several others.
In spite of the common usage, none of these systems were simply named
“DOS” (a name given only to an unrelated IBM mainframe operating system
in the 1960s). A number of unrelated, non-x86 microcomputer disk operating
systems had “DOS” in their name, and are often referred to simply as “DOS”
when discussing machines that use them (e.g. AmigaDOS, AMSDOS,
ANDOS, Apple DOS, Atari DOS, Commodore DOS, CSI-DOS, ProDOS,
and TRS-DOS). While providing many of the same operating system
functions for their respective computer systems, programs running under any
one of these operating systems would not run under others.
Windows can usually detect when a system file is missing and replace it for
you without any involvement on your part. You typically won’t even be
notified when it happens. But even with this ability, system files can become
corrupted or the wrong versions of system files can get installed by errant
applications. Sometimes, these problems slip by Windows unnoticed.
Windows includes the command line tool System File Checker, which
scans several thousand basic Windows files, comparing them against the
original versions that shipped with Windows or depending on the files that
have been updated through Windows Updates. If System File Checker finds a
mismatch, it replaces the original file.
To run the tool, just type sfc at the command prompt followed by a
space and then any of the next common options:
/scannow. This performs an immediate scan of your system and
will replace files as necessary. You may need to restart Windows
when it’s done if it finds problems.
/scanonce. This performs a scan the next time you restart your
system.
/scanboot. This schedules a scan to be performed every time you
restart your system.
Revert. This returns the System File Checker to its default settings.
You can use it to turn off the /scanboot option, for example.
CHECK DISK
Check Disk attempts to repair file system errors, locate bad sectors, and
recover readable information from those bad sectors. If you ever start
Windows and it tells you that it’s scanning your hard disks before starting up,
that’s Check Disk at work. When Windows detects certain types of errors, it
schedules a scan all by itself.
It takes a long time to run, especially if you let it scan the entire hard
disk, including free space, so it’s not really the kind of tool you want to run
regularly.
You can run Check Disk by typing chkdsk at the command prompt,
followed by a space, and then any of these options:
Volume. If you want to check a whole drive, just type the drive
letter.
Filename. You can also use chkdsk to check a single file or group
of files.
/F. Run it with this option to have chkdsk go ahead and fix those
errors.
/R. This option forces chkdsk to locate bad sectors and recover
information from them. If chkdsk cannot lock the disk (which it
usually can’t since you’re actually using Windows), it will prompt
you run the command the next time you restart Windows. This is
the option you’ll use for the most thorough scan because running it
also implies that you’re running the /F option.
If you run chkdsk with no extra options, it will just perform a scan and
give you a report without actually changing anything. So, you’ll need to
specify a volume or file name and one of the other options to make any fixes.
Here’s a common example. If you want chkdsk to scan your C: drive, locate
bad sectors, recover information, and map over those bad sectors, type:
chkdsk C: /R
IPCONFIG
Ipconfig lets you view and work with TCP/IP information. You can use it
to check your computer’s IP address, have it release or renew that IP address
if it’s automatically assigned, and even purge the local DNS cache.
To use it, just type ipconfig at the command line. By itself, the command
shows you IP addressing information about each of the network adapters on
your computer. It may show several different adapters, so you’ll have to do a
little scouting to find the one you’re looking for. You’ll typically see a
Wireless LAN adapter (for your wireless connection) and an Ethernet adapter
(for your wired connection), and probably a few tunnel, virtual, or VPN
adapters, depending on your setup. The information it shows you includes the
IP address, physical (or MAC) address, default gateway, and subnet assigned
to the adapter.
You can also add any of the following options to the ipconfig command
by typing ipconfig , followed by a space, and then the option.
/all. This option shows you all the same information as just running
the ipconfig command by itself, plus a whole bunch more, such as
whether the adapter is automatically assigned an IP address from a
DHCP server, when that address was assigned, and when it expires.
/release. Use this option to release all DHCP-assigned IP addresses.
Note that your network will not work after this and typically you’ll
need use the /renew command afterward.
/renew. Use this option to release and then immediately try to
renew all DHCP-assigned information. This is probably the option
you’ll use most, as it forces your computer to reconnect to your
router or to your ISP’s servers (depending on your setup). It can be
really helpful when troubleshooting connectivity problems.
/flushdns. This option purges the local DNS cache. DNS is used to
translate the more human-readable computer names and web
addresses we use into IP addresses. The cache is DNS information
stored locally on your computer so your computer doesn’t have to
look it up on a DNS server every time. Sometimes, flushing the
DNS cache can resolve problems where you have network
connectivity, but can’t reach some computers or websites by name.
DRIVERQUERY
The driverquery command generates a list of all hardware drivers
installed in Windows. It’s good for giving you a report about installed drivers
that you can save for later reference or for investigating the version number of
a currently installed driver so that you can make a better decision should you
be thinking of updating.
Typed by itself, driverquery just generates a list of drivers that you can
scroll through. As usual, the power comes from the options you can add:
/s. This option lets you specify the name or IP address of a remote
computer so that you investigate the drivers it has installed.
/si. This option shows you the digital signature information for
drivers.
/fo. This is really the key option you’ll use with driverquery. It lets
you specify the format in which information is displayed so that
you can more effectively save it as a report. After typing /fo add
one of the following options: TABLE (the default view), LIST
(which lists each driver with all its information one after the other),
and CSV (which shows data as comma separated values).
To save a report, you just need to pipe the information to a file instead of
displaying it onscreen. To do that add filename.extension to the end of the
command. Here’s an example of perhaps the most useful way to use the
command:
driverquery /fo CSV > drivers.csv
That queries all drivers, formats the result as comma separated values,
and then saves them to a file named drivers.csv. You can then import that
CSV file into Excel or another spreadsheet program to see a nicely-formatted
report of all your installed drivers.
ACALC
External - PC DOS 7
Calculates the value of a mathematical expression.
ACALC [/T[:]format] expression /T Specifies the output format type format
D=Decimal (default) B=Binary O=Octal X=heXadecimal A=All (decimal,
binary, octal, and hexadecimal) expression Specifies a valid numeric
expression.Numbers prefixed with ‘b’, ‘o’, and ‘x’ are assumed to be binary, octal,and
hexadecimal respectively. Decimal numbers are not prefixed.
APPEND
External - DOS 3.3 and above
Allows programs to open data files in specified directories as if they
were in the current directory.
APPEND [[drive:]path[;…]] [/X[:ON | :OFF]] [/PATH:ON | /PATH:OFF] [/E]APPEND ;
[drive:]path Specifies a drive and directory to append. /X:ON Applies appended
directories to file searches and application execution. /X:OFF Applies
appended directories only to requests to open files. /X:OFF is the default setting.
/PATH:ON Applies appended directories to file requests that already specify a
path. /PATH:ON is the default setting. /PATH:OFF Turns off the effect of /PATH:ON.
/E Stores a copy of the appended directory list in an environment variable
named APPEND. /E may be used only the first time you use APPEND after
starting your system.Type APPEND ; to clear the appended directory list.Type APPEND
without parameters to display the appended directory list.
ASSIGN
External - DOS 2.0 and above
Further information: Drive letter assignment
Redirects requests for disk operations on one drive to a different drive.
ASSIGN [x[:]=y[:][…]]ASSIGN /STATUS x Specifies the drive letter to reassign.
y Specifies the drive that x: will be assigned to. /STATUS Displays current drive
assignments.Type ASSIGN without parameters to reset all drive letters to
originalassignments.
ATTRIB
External - DOS 3.0 and above
Displays or changes file attributes.
ATTRIB [+R | -R] [+A | -A] [+S | -S] [+H | -H] [[drive:][path]filename] [/S] + Sets an
attribute. - Clears an attribute. R Read-only file attribute. A Archive file attribute.
S System file attribute. H Hidden file attribute. /S Processes files in all directories in
the specified path.
BACKUP
External - DOS 2.0 and above
Backs up one or more files from one disk to another.
BACKUP source destination-drive: [/S] [/M] [/A] [/F[:size]] [/D:date[/T:time]] [/L[:
[drive:][path]logfile]] source Specifies the file(s), drive, or directory to back up.
destination-drive: Specifies the drive to save backup copies onto. /S Backs up
contents of subdirectories. /M Backs up only files that have changed since the
last backup. /A Adds backup files to an existing backup disk. /F:
[size] Specifies the size of the disk to be formatted. /D:date Backs up only
files changed on or after the specified date. /T:time Backs up only
files changed at or after the specified time. /L[:[drive:]
[path]logfile] Creates a log file and entry to record the backup
operation.
BREAK
Internal - DOS 2.0 and above
Sets or clears extended CTRL+C checking.
BREAK [ON | OFF]Type BREAK without a parameter to display the current BREAK
setting.
CALL
Internal - DOS 3.3 and above
Calls one batch program from another.
CALL [drive:][path]filename [batch-parameters] batch-parameters Specifies any
command-line information required by the batch program.
CHCP
Internal - DOS 3.3 and above
Displays or sets the active code page number.
CHCP [nnn] nnn Specifies a code page number.Type CHCP without a parameter to
display the active code page number.
CHDIR or CD
Internal - DOS 2.0 and above
Displays the name of or changes the current directory.
CHDIR [drive:][path]CHDIR[..]CD [drive:][path]CD[..] .. Specifies that you want to
change to the parent directory.Type CD drive: to display the current directory in the
specified drive.Type CD without parameters to display the current drive and directory.
CHKDSK
External - DOS 1.0 and above
Checks a disk and displays a status report.
CHKDSK [drive:][[path]filename] [/F] [/V] [drive:][path] Specifies the drive and
directory to check. filename Specifies the file(s) to check for fragmentation.
/F Fixes errors on the disk. /V Displays the full path and name of every
file on the disk.Type CHKDSK without parameters to check the current disk.
CHOICE
External - DOS 6.0 and above
Waits for you to choose one of a set of choices.
CHOICE [/C[:]choices] [/N] [/S] [/T[:]c,nn] [text]/C[:]choices Specifies allowable keys.
Default is YN./N Does not display choices and ? at end of prompt string./S
Treats choice keys as case sensitive./T[:]c,nn Defaults choice to c after <nn>
seconds.text Prompts string to display.ERRORLEVEL is set to offset of key you
press in choices.
CLS
Internal - DOS 2.0 and above
Clears the screen.
CLS
COMMAND.COM COMMAND
External - DOS 1.0 and above
Starts a new copy of the DOS Command Interpreter.
COMMAND [[drive:]path] [device] [/E:nnnnn] [/P [/MSG]] [/H] [/O] [/Y [/C
command | /K command]] [drive:]path Specifies the directory containing
COMMAND.COM file. device Specifies the device to use for command input and
output. /E:nnnnn Sets the initial environment size to nnnnn bytes. /P Makes
the new Command Interpreter permanent (can’t exit). /MSG Stores all error
messages in memory (requires /P). /H Loads the Command Interpreter into a
UMB if available. /O Disables overwrite prompt on COPY,XCOPY,and MOVE
commands. /Y Steps through the batch program specified by /C or /K. /C
command Executes the specified command and returns. /K command Executes the
specified command and continues running.The /P and /MSG switches may be used only
when COMMAND is started by usingthe SHELL command in the CONFIG.SYS file.
COMP
External - DOS 1.0 and above
Compares the contents of two files or sets of files.
COMP [data1] [data2] [/D] [/A] [/L] [/N=number] [/C] data1 Specifies location and
name(s) of first file(s) to compare. data2 Specifies location and name(s) of second files
to compare. /D Displays differences in decimal format. This is the default
setting. /A Displays differences in ASCII characters. /L Displays line numbers
for differences. /N=number Compares only the first specified number of lines in each
file. /C Disregards case of ASCII letters when comparing files.To compare sets of
files, use wildcards in data1 and data2 parameters.
COPY
Internal - DOS 1.0 and above
Copies one or more files to another location.
COPY [/A | /B] source [/A | /B] [+ source [/A | /B] [+ …]] [destination [/A | /B]] [/V] [/Y |
/-Y] source Specifies the file or files to be copied. /A Indicates an ASCII text
file. /B Indicates a binary file. destination Specifies the directory and/or filename
for the new file(s). /V Verifies that new files are written correctly. /Y
Suppresses prompting to confirm you want to overwrite an existing destination
file. /-Y Causes prompting to confirm you want to overwrite an existing
destination file.The switch /Y may be preset in the COPYCMD environment variable.To
append files, specify a single file for destination, but multiple filesfor source (using
wildcards or file1+file2+file3 format).
CTTY
Internal - DOS 2.0 and above
Changes the terminal device used to control your system.
CTTY device device The terminal device you want to use, such as COM1.
DATE
External - DOS 1.0
Internal - DOS 1.1 and above
Displays or sets the date.
DATE [date]Type DATE without parameters to display the current date setting anda
prompt for a new one. Press ENTER to keep the same date.
DEBUG
External - DOS 1.0 and above
Runs Debug, a program testing and editing tool.
DEBUG [[drive:][path]filename [testfile-parameters]] [drive:][path]filename Specifies
the file you want to test. testfile-parameters Specifies command-line information
required by the file you want to test.After Debug starts, type ? to display a
list of debugging commands.
DEL or ERASE
Internal - DOS 1.0 and above
Deletes one or more files.
DEL [drive:][path]filename [/P]ERASE [drive:][path]filename [/P] [drive:]
[path]filename Specifies the file(s) to delete. Specify multiple files by
using wildcards. /P Prompts for confirmation before deleting each file.
DELTREE
External - DOS 6.0 and above
Deletes a directory and all the subdirectories and files within it.
To Delete one or more directories:DELTREE [/Y] [drive:]path [[drive:]path[…]]
/Y Suppresses prompting to confirm whether you want to delete the
subdirectory. [drive:]path Specifies the name of the directory you want to delete.Note:
Use DELTREE with caution. Every file and subdirectory within thespecified directory
will be deleted.
DIR
Internal - DOS 1.0 and above
Displays a list of files and subdirectories in a directory.
DIR [drive:][path][filename] [/P] [/W] [/A[[:]attribs]] [/O[[:]sortord]] [/S] [/B] [/L]
[drive:][path][filename] Specifies drive, directory, and files to list. /P Pauses after
each full screen of information. /W Uses wide list format. /A Displays files with
specified attributes. attribs D Directories R Read-only files H Hidden
files S System files A Files ready to archive - Prefix meaning “not” /O Lists
by files in sorted order. sortord N By name (alphabetic) S By size (smallest
first) E By extension (alphabetic) D By date & time (earliest first) G
Group directories first - Prefix to reverse order /S Displays files in specified
directory and all subdirectories. /B Uses bare format (no heading information or
summary). /L Uses lowercase.Switches may be preset in the DIRCMD environment
variable. Overridepreset switches by prefixing any switch with - (hyphen)—for example,
/-W.To remove the commas from the DIR output, use the NO_SEP environment variable.
DISKCOMP
External - DOS 1.0 and above
Compares the contents of two floppy disks.
DISKCOMP [drive1: [drive2:]] [/1] [/8] /1 Compares the first side of the disks. /8
Compares only the first eight sectors of each track.
DISKCOPY
External - DOS 1.0 and above
Copies the contents of one floppy disk to another.
DISKCOPY [drive1: [drive2:]] [/1] [/V] [/M] /1 Copies only the first side of the disk.
/V Verifies that the information is copied correctly. /M Force multi-pass copy using
memory only.The two floppy disks must be the same type.You may specify the same drive
for drive1 and drive2.
DOSKEY
External - DOS 5.0 and above
Edits command lines, recalls DOS commands, and creates macros.
DOSKEY [/REINSTALL] [/BUFSIZE=size] [/MACROS] [/HISTORY] [/INSERT |
/OVERSTRIKE] [macroname=[text]] /REINSTALL Installs a new copy of Doskey.
/BUFSIZE=size Sets size of command history buffer. /MACROS Displays all Doskey
macros. /HISTORY Displays all commands stored in memory. /INSERT Specifies
that new text you type is inserted in old text. /OVERSTRIKE Specifies that new text
overwrites old text. macroname Specifies a name for a macro you create. text
Specifies commands you want to record.UP and DOWN ARROWS recall commands;
ESC clears command line; F7 displayscommand history; ALT+F7 clears command
history; F8 searches commandhistory; F9 selects a command by number; ALT+F10 clears
macro definitions.The following are some special codes in Doskey macro
definitions:$T Command separator. Allows multiple commands in a macro.$1-$9
Batch parameters. Equivalent to %1-%9 in batch programs.$* Symbol replaced by
everything following macro name on command line.
DRVLOCK
External - PC DOS 5.02 and above
Locks the drive or socket so that media cannot be removed.
DRVLOCK [drive: | socket:] [/ON | /OFF] /ON Sets the lock on. /OFF Sets
the lock off.
DYNALOAD
External - PC DOS 7
Load a device driver after system startup.
DYNALOAD filename [parameters] filename Specifies the name of the device driver
to load. parameters Specifies any parameters for the device driver.
E
External - PC DOS 6.1 and above
Starts PC DOS editor, which creates and changes ASCII files.
E [/Q] [/B] [/S] [/D] [/I] [/C] [/A] [/DM] [/80 |/132] [d:][path][filespec] [=filespec]
[‘command’] /Q Turns off display of “Loading ..” message. /B Displays files in
browse (read-only) mode. /S Uses EMS (or hardfile if no EMS is available) to edit
files too large for conventional memory. /D Forces file to be loaded from
disk. /I Edits STACKER.INI file. /C Edits CONFIG.SYS file. /A Edits
AUTOEXEC.BAT file. /DM Disables Mouse. /80 Enables 80 column, 16 color
text video (CGA/EGA/MCGA/VGA/SVGA/XGA). /132 Enables 132 column, 16
color text video (XGA). [d:][path][filespec] Specifies drive, directory, and file to edit.
= Is shorthand for “same path as last specified” at the DOS prompt, or “same
as current file’s” at the editor commandline. For example, E
\PAS\LANG\FOO.PAS =FOO.BAK will load the two files FOO.PAS and
FOO.BAK, both from the directory \PAS\LANG. ‘command’ Specifies a startup
command. For example, E \FOO.PAS ‘ALL /IF’ will load the file FOO.PAS and
then execute the ALL command on this file.Switches may be preset in the E
environment variable.
E is only included with PC DOS versions and replaces the MS-DOS editor
EDIT.
ECHO
Internal - DOS 2.0 and above
Displays messages, or turns command-echoing on or off.
ECHO [ON | OFF] ECHO [message]Type ECHO without parameters to display the
current echo setting.
EDLIN
External - DOS 1.0 and above
Line-oriented text editor.
EDLIN [drive:][path]filename [/B] /B Ignores end-of-file (CTRL+Z) characters.
EJECT
External - PC DOS 5.02 and above
Ejects the media from a drive.
EJECT [drive:]
EMM386
External - DOS 5.0 and above
Turns on or off EMM386 expanded memory support.
EMM386 [ON | OFF | AUTO] [W=ON | W=OFF] ON | OFF | AUTO Activates or
suspends EMM386.EXE device driver, or places it in auto mode. W=ON |
OFF Turns on or off Weitek coprocessor support.
EXE2BIN
External - DOS 1.0 and above
Converts .EXE (executable) files to binary format.
EXE2BIN [drive1:][path1]input-file [[drive2:][path2]output-file] input-file Specifies the
.EXE file to be converted. output-file Specifies the binary file to be created.
EXIT
Internal - DOS 2.0 and above
Quits the COMMAND.COM program (command interpreter).
EXIT
FASTOPEN
External - DOS 3.3 to DOS 6.3
Decreases the amount of time needed to open frequently used files and directories.
FASTOPEN drive:[[=]n] [drive:[[=]n][ …]] [/X] drive: Specifies the hard disk drive you
want Fastopen to work with. n Specifies the maximum number of file locations
Fastopen retains in its filename cache. /X Creates the filename cache in
expanded memory.
FC
External - DOS 3.3 and above
Compares two files or sets of files and displays the differences between them.
FC [/A] [/C] [/L] [/LBn] [/N] [/T] [/W] [/nnnn] [drive1:][path1]filename1 [drive2:]
[path2]filename2FC /B [drive1:][path1]filename1 [drive2:][path2]filename2 /A
Displays only first and last lines for each set of differences. /B Performs a binary
comparison. /C Disregards the case of letters. /L Compares files as ASCII text.
/LBn Sets the maximum consecutive mismatches to the specified number of lines.
/N Displays the line numbers on an ASCII comparison. /T Does not expand tabs to
spaces. /W Compresses white space (tabs and spaces) for comparison. /nnnn Specifies
the number of consecutive lines that must match after a mismatch.
FDISK
External - DOS 2.0 and above
Configures a hard disk for use with DOS.
FDISK [/STATUS] /STATUS Displays the status of the fixed disk drive
FIND
External - DOS 2.0 and above
Searches for a text string in a file or files.
FIND [/V] [/C] [/N] [/I] [/S] “string” [[drive:][path]filename[ …]] /V Displays all
lines NOT containing the specified string. /C Displays only the count of lines
containing the string. /N Displays line numbers with the displayed lines. /I
Ignores the case of characters when searching for the string. /S Search subdirectories
also. “string” Specifies the text string to find. [drive:][path]filename Specifies a
file or files to search.If a pathname is not specified, FIND searches the text typed at the
promptor piped from another command.
FOR
Internal - DOS 2.0 and above
Runs a specified command for each file in a set of files.
FOR %variable IN (set) DO command [command-parameters] %variable Specifies a
replaceable parameter. (set) Specifies a set of one or more files. Wildcards may be
used. command Specifies the command to carry out for each file. command-
parameters Specifies parameters or switches for the specified command.To use the
FOR command in a batch program, specify %%variable instead of%variable.
FORMAT
External - DOS 1.0 and above
Formats a disk for use with DOS.
FORMAT drive: [/V[:label]] [/Q] [/U] [/F:size] [/B | /S] [/C]FORMAT drive: [/V[:label]]
[/Q] [/U] [/T:tracks /N:sectors] [/B | /S] [/C]FORMAT drive: [/V[:label]] [/Q] [/U] [/1] [/4]
[/B | /S] [/C]FORMAT drive: [/Q] [/U] [/1] [/4] [/8] [/B | /S] [/C] /V[:label] Specifies the
volume label. /Q Performs a quick format. /U Performs an unconditional
format. /F:size Specifies the size of the floppy disk to format (such as 160,
180, 320, 360, 720, 1.2, 1.44, 2.88). /B Allocates space on the formatted disk for
system files. /S Copies system files to the formatted disk. /T:tracks Specifies the
number of tracks per disk side. /N:sectors Specifies the number of sectors per track.
/1 Formats a single side of a floppy disk. /4 Formats a 5.25-inch 360K floppy
disk in a high-density drive. /8 Formats eight sectors per track. /C Revert to
less conservative handling of bad blocks.
/Q and /U are only available in DOS 5 and above. /C is only available in DOS
6 and above.
FORMAT replaced the internal command CLEAR in 86-DOS.
GOTO
Internal - DOS 2.0 and above
Directs DOS to a labelled line in a batch program.
GOTO label label Specifies a text string used in the batch program as a label.You type a
label on a line by itself, beginning with a colon.
GRAFTABL
External - DOS 3.0 and above
Enables DOS to display an extended character set in graphics mode.
GRAFTABL [xxx]GRAFTABL /STATUS xxx Specifies a code page number.
/STATUS Displays the current code page selected for use with GRAFTABL.
GRAPHICS
External - DOS 2.0 and above
Loads a program that can print graphics.
GRAPHICS [type] [[drive:][path]filename] [/R] [/B] [/LCD] [/PRINTBOX:STD |
/PRINTBOX:LCD] type Specifies a printer type. [drive:][path]filename
Specifies the file containing information on supported printers. /R Prints white on
black as seen on the screen. /B Prints the background in color for COLOR4 and
COLOR8 printers. /LCD Prints using LCD aspect ratio. /PRINTBOX:STD |
/PRINTBOX:LCD Specifies the print-box size, either STD or LCD.
HELP
External - DOS 5.0 and above
Displays command help.
HELP [topic]
• MS-DOS versions use QBASIC.EXE and QuickHelp files for its help
system.
• PC DOS versions use VIEW.EXE and Information Presentation
Facility files for its help system.
IF
Internal - DOS 2.0 and above
Performs conditional processing in batch programs.
IF [NOT] ERRORLEVEL number commandIF [NOT] string1==string2 commandIF
[NOT] EXIST filename command NOT Specifies that DOS should carry out the
command only if the condition is false. ERRORLEVEL number Specifies a
true condition if the last program run returned an exit code equal to or greater
than the number specified. command Specifies the command to carry out if the
condition is met. string1==string2 Specifies a true condition if the specified
text strings match. EXIST filename Specifies a true condition if the
specified filename exists.
INTERLNK
External - DOS 5.02 and above
Displays status of INTERLNK-INTERSVR redirected drives.
INTERLNK [client=[server]] client Specifies a client drive to redirect to a server
drive. Cancels redirection if no server drive is specified. server
Specifies a server drive to redirect to a client drive. Type INTERLNK with no
parameters to show INTERLNK status.
INTERSVR
External - DOS 5.02 and above
Provides serial or parallel file transfer and printing capabilities via redirected drives.
INTERSVR [drive:[…]] [/X=drive:[…]] [/LPT[:][n | address]] [/COM[:][n | address]]
[/baud:rate] [/v] [/b] drive: Specifies the drive(s) to redirect (by default,
all drives are redirected). /X=drive: Specifies the drive(s) to exclude. /LPT[n]
Specifies a port to scan. (/LPT scans all LPT ports). /LPT[address] Specifies a port
address to scan. /COM[n] Specifies a port to scan. (/COM scans all COM ports).
/COM[address] Specifies a port address to scan. /BAUD:rate Set a maximum serial
baud rate. /B Displays the INTERLNK server screen in black and white.
/V Prevents conflicts with a computer’s timer. Specify this switch if you
have a serial connection between computers and one of them stops running
when you use INTERLNK.INTERSVR /RCOPYCopies INTERLNK files from one
computer to another, provided that thecomputers’ serial ports are connected with a 7-wire
null-modem cable.
JOIN
External - DOS 3.1 and above
Joins a disk drive to a directory on another drive.
JOIN [drive1: [drive2:]path]JOIN drive1: /D drive1: Specifies a disk drive that will
appear as a directory on drive2. drive2: Specifies a drive to which you
want to join drive1. path Specifies the directory to which you want to join drive1.
It must be empty and cannot be the root directory. /D Cancels any
previous JOIN commands for the specified drive.Type JOIN without parameters to list
currently joined drives.
KEYB
External - DOS 3.3 and above
Configures a keyboard for a specific language.
KEYB [xx[,[yyy][,[drive:][path]filename]]] [/E] [/ID:nnn] xx Specifies a
two-letter keyboard code. yyy Specifies the code page for the character set.
[drive:][path]filename Specifies the keyboard definition file. /E Specifies
that an enhanced keyboard is installed. /ID:nnn Specifies the keyboard in use.
LABEL
External - DOS 3.0 and above
Creates, changes, or deletes the volume label of a disk.
LABEL [drive:][label]
LOADFIX
External - DOS 5.0 and above
Loads a program above the first 64K of memory, and runs the program.
LOADFIX [drive:][path]filenameUse LOADFIX to load a program if you have received
the message”Packed file corrupt” when trying to load it in low memory.
LOADHIGH or LH
Internal - DOS 5.0 and above
Loads a program into the upper memory area.
LOADHIGH [drive:][path]filename [parameters]LOADHIGH [/L:region1[,minsize1]
[;region2[,minsize2]…]] [drive:][path]filename [parameters]/L:region1[,minsize1]
[;region2[,minsize2]]… Specifies the region(s) of memory into which to
load the program. Region1 specifies the number of the first memory region;
minsize1 specifies the minimum size, if any, for region1. Region2 and minsize2
specify the number and minimum size of the second region, if any. You can
specify as many regions as you want.[drive:][path]filename Specifies the location
and name of the program.parameters Specifies any command-line information required
by the program.
MEM
External - DOS 4.0 and above
Displays the amount of used and free memory in your system.
MEM [/CLASSIFY | /DEBUG | /FREE | /MODULE modulename] [/PAGE] /CLASSIFY
or /C Classifies programs by memory usage. Lists the size of programs,
provides a summary of memory in use, and lists the largest memory block
available. /DEBUG or /D Displays status of all modules in memory, internal
drivers, and other information. /FREE or /F Displays information about the
amount of free memory left in both conventional and upper memory.
/MODULE or /M Displays a detailed listing of a module’s memory use. This
option must be followed by the name of a module, optionally separated from
/M by a colon. /PAGE or /P Pauses after each full screen of information.
MIRROR
External - DOS 5.0 and above
Records information about one or more disks.
MIRROR [drive:[ …]] [/1] [/Tdrive[-entries][ …]]MIRROR [/U]MIRROR [/PARTN]
drive: Specifies the drive for which you want to save information. /1 Saves only
the latest disk information (does not back up previous information). /Tdrive
Loads the deletion-tracking program for the specified drive. -entries Specifies
maximum number of entries in the deletion-tracking file. /U Unloads the
deletion-tracking program. /PARTN Saves hard disk partition information to a floppy
diskette.
MKDIR or MD
Internal - DOS 2.0 and above
Creates a directory.
MKDIR [drive:]pathMD [drive:]path
MODE
External - DOS 1.0 and above
Configures system devices.
Printer port: MODE LPTn[:] [COLS=c] [LINES=l] [RETRY=r]Serial port: MODE
COMm[:] [BAUD=b] [PARITY=p] [DATA=d] [STOP=s] [RETRY=r]Device Status:
MODE [device] [/STATUS]Redirect printing: MODE LPTn[:]=COMm[:]Prepare code
page: MODE device CP PREPARE=((yyy[…]) [drive:][path]filename)Select code page:
MODE device CP SELECT=yyyRefresh code page: MODE device CP REFRESHCode
page status: MODE device CP [/STATUS]Display mode: MODE [display-adapter]
[,n] MODE CON[:] [COLS=c] [LINES=n]Typematic rate: MODE CON[:]
[RATE=r DELAY=d]
MORE
External - DOS 2.0 and above
Displays output one screen at a time.
MORE < [drive:][path]filenamecommand-name | MORE [drive:][path]filename
Specifies a file to display one screen at a time. command-name Specifies a
command whose output will be displayed.
MOVE
External - DOS 6.0 and above
Moves files and renames files and directories.
To move one or more files:MOVE [/Y | /-Y] [drive:][path]filename1[,…] destinationTo
rename a directory:MOVE [drive:][path]dirname1 dirname2 /Y Suppresses
prompting to confirm overwriting of the destination. /-Y Causes prompting to confirm
overwriting of the destination. The switch /Y may be present in the COPYCMD
environment variable. This may be overridden with /-Y on the command line.
[drive:][path]filename1 Specifies the location and name of the file or files
you want to move. destination Specifies the new location of the file.
Destination can consist of a drive letter and colon, a
directory name, or a combination. If you are moving only
one file, you can also include a filename if you want to
rename the file when you move it. [drive:][path]dirname1 Specifies the directory you
want to rename. dirname2 Specifies the new name of the directory.
MSCDEX
External - DOS 6.0 and above
Loads the CD-ROM support utility.
MSCDEX /D:driver … [/E] [/K] [/L:letter] [/M:buffers] [/S] [/V] /D:driver Specifies
name of CD-ROM driver /E Load buffers in expanded memory (EMS) /K
Load Kanji support /L:letter Specifies first drive letter to use /M:buffers Specifies
number of sector buffers /S Load server environment support /V Display
verbose memory usage statistics
MSD
External - MS-DOS 6.0 and above
Provides detailed technical information about your computer.
MSD [/I] [/F[drive:][path]filename] [/P[drive:][path]filename] [/S[drive:][path]
[filename]]MSD [/B][/I] /B Runs MSD using a black and white color
scheme. /I Bypasses initial hardware detection. /F[drive:][path]filename
Requests input and writes an MSD report to the specified file. /P[drive:]
[path]filename Writes an MSD report to the specified file without first
requesting input. /S[drive:][path][filename] Writes a summary MSD report to the
specified file. If no filename is specified, output is to
the screen.
NLSFUNC
External - DOS 3.3 and above
Loads country-specific information.
NLSFUNC [[drive:][path]filename] [drive:][path]filename Specifies the file containing
country-specific information.
PATH
Internal - DOS 2.0 and above
Displays or sets a search path for executable files.
PATH [[drive:]path[;…]]PATH ;Type PATH ; to clear all search-path settings and direct
DOS to searchonly in the current directory.Type PATH without parameters to display the
current path.
PAUSE
Internal - DOS 1.0 and above
Suspends processing of a batch program and displays the message “Press any key to
continue….”
PAUSE
POWER
External - DOS 5.02 and above
Reduces power used by your computer.
POWER [ADV[:MAX | REG | MIN] | STD | OFF] ADV[:MAX | REG | MIN] —
Reduces power by monitoring applications and hardware devices. MAX provides the
most power conservation, REG provides average power conservation, and MIN
provides the least conservation. STD — Reduces power by monitoring hardware
devices. OFF — Turns off power management.
PRINT
External - DOS 2.0 and above
Prints a text file while you are using other DOS commands.
PRINT [/D:device] [/B:size] [/U:ticks1] [/M:ticks2] [/S:ticks3] [/Q:qsize] [/T] [[drive:]
[path]filename[ …]] [/C] [/P] /D:device Specifies a print device. /B:size Sets the
internal buffer size, in bytes. /U:ticks1 Waits the specified maximum number of clock
ticks for the printer to be available. /M:ticks2 Specifies the maximum number of
clock ticks it takes to print a character. /S:ticks3 Allocates the scheduler the
specified number of clock ticks for background printing. /Q:qsize Specifies the
maximum number of files allowed in the print queue. /T Removes all files from the
print queue. /C Cancels printing of the preceding filename and subsequent
filenames. /P Adds the preceding filename and subsequent filenames to the
print queue.Type PRINT without parameters to display the contents of the print
queue.
PROMPT
Internal - DOS 2.0 and above
Changes the DOS command prompt.
PROMPT [text] text Specifies a new command prompt.Prompt can be made up of
normal characters and the following special codes: $Q = (equal sign) $$ $ (dollar
sign) $T Current time $D Current date $P Current drive and path $V DOS version
number $N Current drive $G > (greater-than sign) $L < (less-than sign) $B |
(pipe) $H Backspace (erases previous character) $E Escape code (ASCII code 27)
$_ Carriage return and linefeedType PROMPT without parameters to reset the prompt to
the default setting.
QBASIC
External - MS-DOS 5.0 and above
Further information: QBASIC
Starts the MS-DOS QBasic programming environment.
QBASIC [/B] [/EDITOR] [/G] [/H] [/MBF] [/NOHI] [[/RUN] [drive:][path]filename]
/B Allows use of a monochrome monitor with a color graphics card. /EDITOR
Starts the MS-DOS editor. /G Provides the fastest update of a CGA screen. /H
Displays the maximum number of lines possible for your hardware. /MBF Converts
the built-in functions MKS$, MKD$, CVS, and CVD to MKSMBF$,
MKDMBF$, CVSMBF, and CVDMBF, respectively. /NOHI Allows the use of a
monitor without high-intensity support. /RUN Runs the specified Basic program
before displaying it. [[drive:][path]filename] Specifies the program file to load or run.
QCONFIG
External - PC DOS 6.1 and above
Displays detailed technical information about your computer.
QCONFIG [/?][/A][/C][/D][/E][/I][/O[file]][/P][/Q] [key=“text”] /? Displays this help
information. /A Displays all Micro Channel adapters supported by QCONFIG. /C
Displays additional detail on async ports. /D Displays a detailed listing of hardware.
/E Displays current environment. /I Displays CONFIG.SYS &
AUTOEXEC.BAT. /O Redirects output to file QCONFIG.OUT. /Ofile Redirects
output to file (anyname). /P Pauses the output between screens. /Q Does not
display redirect message.key=“text” Defines key with text to appear in output (must be
last option).
QCONFIG is only included with PC DOS versions and replaces the Microsoft
MSD utility.
RECOVER
External - DOS 2.0 to DOS 5.0
Recovers readable information from a bad or defective disk.
RECOVER [drive:][path]filenameRECOVER drive:
REM
Internal - DOS 1.0 and above
Records comments (remarks) in a batch file or CONFIG.SYS.
REM [comment]
RENAME or REN
Internal - DOS 1.0 and above
Renames a file or files.
RENAME [drive:][path]filename1 filename2REN [drive:][path]filename1 filename2Note
that you cannot specify a new drive or path for your destination file.Use MOVE to move
files from one directory to another, or to rename a directory.
RENAME (but not its alias REN) originated as an internal command in 86-
DOS.
REPLACE
External - DOS 3.2 and above
Replaces files.
REPLACE [drive1:][path1]filename [drive2:][path2] [/A] [/P] [/R] [/W]REPLACE
[drive1:][path1]filename [drive2:][path2] [/P] [/R] [/S] [/W] [/U] [drive1:]
[path1]filename Specifies the source file or files. [drive2:][path2] Specifies the
directory where files are to be replaced. /A Adds new files
to destination directory. Cannot use with /S or /U switches.
/P Prompts for confirmation before replacing a file or
adding a source file. /R Replaces read-only files as well as
unprotected files. /S Replaces files in all subdirectories of
the destination directory. Cannot use with the /A switch.
/W Waits for you to insert a disk before beginning. /U
Replaces (updates) only files that are older than source files. Cannot use
with the /A switch.
RESTORE
External - DOS 2.0 and above
Restores files that were backed up by using the BACKUP command.
RESTORE drive1: drive2:[path[filename]] [/S] [/P] [/B:date] [/A:date] [/E:time]
[/L:time] [/M] [/N] [/D] drive1: Specifies the drive on which the backup files are stored.
drive2:[path[filename]] Specifies the file(s) to restore. /S Restores files in all
subdirectories in the path. /P Prompts before restoring read-only files or files changed
since the last backup (if appropriate attributes are set). /B Restores only files
last changed on or before the specified date. /A Restores only files changed on or
after the specified date. /E Restores only files last changed at or earlier than the
specified time. /L Restores only files changed at or later than the specified
time. /M Restores only files changed since the last backup. /N Restores only files
that no longer exist on the destination disk. /D Displays files on the backup disk that
match specifications.
REXX
External - PC DOS 7
Further information: REXX
Execute a REXX program.
REXX filename [parameters] filename Specifies the name of the REXX program to
execute. parameters Specifies any parameters for the REXX program.
REXXDUMP
External - PC DOS 7
Dump the variables of an active REXX procedure.
REXXDUMP
RMDIR or RD
Internal - DOS 2.0 and above
Removes (deletes) a directory.
RMDIR [drive:]pathRD [drive:]path
SCANDISK
External - MS-DOS 6.2 and above
Runs the ScanDisk disk-repair program.
To check and repair a drive, use the following syntax: SCANDISK [drive: | /ALL]
[/CHECKONLY | /AUTOFIX [/NOSAVE]] [/SURFACE]To check and repair an
unmounted DriveSpace compressed volume file, use: SCANDISK
drive:\DRVSPACE.nnn [/CHECKONLY | /AUTOFIX[/NOSAVE]]To examine a file for
fragmentation, use the following syntax: SCANDISK /FRAGMENT [drive:]
[path]filenameTo undo repairs you made previously, use the following syntax:
SCANDISK /UNDO [drive:]For [drive:], specify the drive containing your Undo
disk./ALL Checks and repairs all local drives./AUTOFIX Fixes damage without
prompting./CHECKONLY Checks a drive, but does not repair any
damage./CUSTOM Configures and runs ScanDisk according to SCANDISK.INI
settings./NOSAVE With /AUTOFIX, deletes lost clusters rather than saving as
files./NOSUMMARY With /CHECKONLY or /AUTOFIX, prevents ScanDisk from
stopping at summary screens./SURFACE Performs a surface scan after
other checks./MONO Configures ScanDisk for use with a monochrome display.To
check and repair the current drive, type SCANDISK without parameters.
SET
Internal - DOS 2.0 and above
Displays, sets, or removes DOS environment variables.
SET [variable=[string]] variable Specifies the environment-variable name. string
Specifies a series of characters to assign to the variable.Type SET without parameters to
display the current environment variables.
SETVER
External - DOS 5.0 and above
Sets the version number that DOS reports to a program.
Display current version table: SETVER [drive:path]Add entry: SETVER
[drive:path] filename n.nnDelete entry: SETVER [drive:path] filename
/DELETE [/QUIET] [drive:path] Specifies location of the SETVER.EXE file.
filename Specifies the filename of the program. n.nn Specifies the DOS
version to be reported to the program. /DELETE or /D Deletes the version-table entry
for the specified program. /QUIET Hides the message typically displayed during
deletion of version-table entry.
SHARE
External - DOS 3.0 and above
Installs file-sharing and locking capabilities on your hard disk.
SHARE [/F:space] [/L:locks] [/NOHMA] /F:space Allocates file space (in bytes) for
file-sharing information. /L:locks Sets the number of files that can be locked at one
time. /NOHMA Don’t load code into the HMA.
SHIFT
Internal - DOS 2.0 and above
Changes the position of replaceable parameters in a batch file.
SHIFT
Smartdrive (SMARTDRV)
External - DOS 6.0 and above
Installs and configures the SMARTDrive disk-caching utility.
SMARTDRV [/X] [[drive[+|-]]…] [/U] [/C | /R] [/L] [/V | /Q | /S] [InitCacheSize
[WinCacheSize]] [/E:ElementSize] [/B:BufferSize]/X Disables write-behind
caching for all drives.drive Sets caching options on specific drive(s). The
specified drive(s) will have write-caching disabled unless you add +.+
Enables write-behind caching for the specified drive.- Disables all caching for the
specified drive./U Do not load CD-ROM caching module./C Writes all
information currently in write-cache to hard disk./R Clears the cache and restarts
SMARTDrive./L Prevents SMARTDrive from loading itself into upper
memory./V Displays SMARTDrive status messages when loading./Q
Does not display status information./S Displays additional information about
SMARTDrive’s status.InitCacheSize Specifies XMS memory (KB) for the
cache.WinCacheSize Specifies XMS memory (KB) for the cache with
Windows./E:ElementSize Specifies how many bytes of information to move at one
time./B:BufferSize Specifies the size of the read-ahead buffer.
SORT
External - DOS 2.0 and above
Sorts input and writes results to the screen, a file, or another device.
SORT [/R] [/+n] < [drive1:][path1]filename1 [> [drive2:][path2]filename2][command |]
SORT [/R] [/+n] [> [drive2:][path2]filename2] /R Reverses the sort order;
that is, sorts Z to A, then 9 to 0. /+n Sorts the file
according to characters in column n. [drive1:][path1]filename1
Specifies a file to be sorted. [drive2:][path2]filename2 Specifies a file where the sorted
input is to be stored. command Specifies a command whose
output is to be sorted.
SUBST
External - DOS 3.1 and above
Associates a path with a drive letter.
SUBST [drive1: [drive2:]path]SUBST drive1: /D drive1: Specifies a virtual drive to
which you want to assign a path. [drive2:]path Specifies a physical drive and path you
want to assign to a virtual drive. /D Deletes a substituted (virtual)
drive.Type SUBST with no parameters to display a list of current virtual drives.
SYS
External - DOS 1.0 and above
Copies DOS system files and command interpreter to a disk you specify.
SYS [drive1:][path] drive2: [drive1:][path] Specifies the location of the system files.
drive2: Specifies the drive the files are to be copied to.
TIME
External - DOS 1.0
Internal - DOS 1.1 and above
Displays or sets the system time.
TIME [time]Type TIME with no parameters to display the current time setting and a
promptfor a new one. Press ENTER to keep the same time.
TREE
External - DOS 2.0 and above
Graphically displays the directory structure of a drive or path.
TREE [drive:][path] [/F] [/A] /F Displays the names of the files in each directory. /A
Uses ASCII instead of extended characters.
TRUENAME
Internal - DOS 4.0 and above
Returns a fully qualified filename.
TRUENAME [drive:][path]filename
type (command)TYPE
Internal - DOS 1.0 and above
Displays the contents of a text file.
TYPE [drive:][path]filename
UNDELETE
External - DOS 5.0 and above
Restores files previously deleted with the DEL command.
UNDELETE [[drive:][path]filename] [/DT | /DS | /DOS]UNDELETE [/LIST | /ALL |
/PURGE[DRIVE] | /STATUS | /LOAD | /UNLOAD /S[DRIVE] | /T[DRIVE]-entrys
]] /LIST Lists the deleted files available to be recovered. /ALL
Recovers files without prompting for confirmation. /DOS Recovers files listed
as deleted by MS-DOS. /DT Recovers files protected by Delete Tracker.
/DS Recovers files protected by Delete Sentry. /LOAD Loads
Undelete into memory for delete protection. /UNLOAD Unloads Undelete from
memory. /PURGE[drive] Purges all files in the Delete Sentry directory.
/STATUS Display the protection method in effect for each drive. /S[drive]
Enables Delete Sentry method of protection. /T[drive][-entrys] Enables Delete Tracking
method of protection.
VER
Internal - DOS 2.0 and above
Displays the DOS version.
VER
The undocumented /R switch displays the revision level and where DOS is
loaded (low, HMA or ROM) in DOS 5 and above.
Version returned:
• MS-DOS up to 6.22, typically derive the DOS version from the DOS
kernel. This may be different from the string it prints when it starts.
• PC DOS typically derive the version from an internal string in
COMMAND.COM (so PC DOS 6.1 COMMAND.COM reports the version
as 6.10, although the kernel version is 6.00.)
• DR-DOS reports whatever value the reserved environment variable
VER holds.
VERIFY
Internal - DOS 2.0 and above
Tells DOS whether to verify that your files are written correctly to a disk.
VERIFY [ON | OFF]Type VERIFY without a parameter to display the current VERIFY
setting.
VOL
Internal - DOS 2.0 and above
Displays the disk volume label and serial number, if they exist.
VOL [drive:]
XCOPY
External - DOS 3.2 and above
Copy entire directory trees.
XCOPY [/Y|/-Y] source [destination] [/A|/M] [/D:date] [/P] [/S] [/E] [/V] [/W] source
Specifies the file(s) to copy. destination Specifies the location and/or name of new files.
/A Copies files with the archive attribute set, doesn’t change the attribute.
/M Copies files with the archive attribute set, turns off the archive
attribute. /D:date Copies files changed on or after the specified date. /P Prompts
you before creating each destination file. /S Copies directories and subdirectories
except empty ones. /E Copies any subdirectories, even if empty. /V Verifies
each new file. /W Prompts you to press a key before copying. /Y Suppresses
prompting to confirm you want to overwrite an existing destination file. /-
Y Causes prompting to confirm you want to overwrite an existing
destination file.The switch /Y may be preset in the COPYCMD environment variable.This
may be overridden with /-Y on the command line
Command Syntax
start [path to the file you want to run or to the EXE file of the program you
want to run]
TITLE (command)
In computing, title is a command that changes the title for the Microsoft
Windows Command Prompt window. It is a shell builtin of the command line
interpreter cmd.exe . The default title is defined in the %COMSPEC%
environment variable. However, since the Win32 console title can also be
defined in the program shortcut, the title is usually set to “Command Prompt”.
Syntax
title [<String>]
Arguments:
• <String> Specifies the title of the Command Prompt window.
Example
The following batch file changes the title of the Command Prompt window to
“Updating files” while the copy command is being executed. After the
command is executed, the text “Files updated” is displayed using the echo
command, and the title of the Command Prompt window is changed back to
“Command Prompt”.
@echo off
title Updating files
copy \server\share\*.txt c:\documents\*.txt
echo Files updated
title Command Prompt
TYPE
In computing, type is a command in various VMS. AmigaDOS, CP/M,
DOS, OS/2 and Microsoft Windows command line interpreters (shells) such
as COMMAND.COM , cmd.exe , 4DOS/4NT and Windows PowerShell. It
is used to display the contents of specified files. It is analogous to the Unix
cat command.
In Windows PowerShell, type is a predefined command alias for the Get-
Content Cmdlet which basically serves the same purpose.
Interesting…
How the FOLDER became the FOLDER
The name folder, presenting an analogy to the file folder used in offices, and
used originally by Apple Lisa, is used in almost all modern operating systems’
desktop environments. Folders are often depicted with icons which visually
resemble physical file folders.
Strictly speaking, there is a difference between a directory, which is a file
system concept, and the graphical user interface metaphor that is used to
represent it (a folder). For example, Microsoft Windows uses the concept of
special folders to help present the contents of the computer to the user in a
fairly consistent way that frees the user from having to deal with absolute
directory paths, which can vary between versions of Windows, and between
individual installations.
If one is referring to a container of documents, the term folder is more
appropriate. The term directory refers to the way a structured list of document
files and directories is stored on the computer. It is comparable to a telephone
directory that contains lists of names, numbers, and addresses but does not
contain the actual documents themselves.
echo (command)
In computing, echo is a command in DOS, OS/2, Microsoft Windows,
Singularity, Unix and Unix-like operating systems that places a string on the
computer terminal. It is typically used in shell scripts and batch files to output
status text to the screen or a file.
Usage example
$ echo This is a test.
This is a test.
$ echo “This is a test.” > ./test.txt
$ cat ./test.txt
This is a test.
Some variants of Unix support options such as -n and -e . These are not
standard due to historical incompatibilities between BSD and System V; the
printf command can be used in situations where this is a problem.
Using ANSI escape code SGR sequences, compatible terminals can print out
colored text:
FGRED=`echo “\033[31m”`
FGCYAN=`echo “\033[36m”`
BGRED=`echo “\033[41m”`
FGBLUE=`echo “\033[35m”`
BGGREEN=`echo “\033[42m”`
NORMAL=`echo “\033[m”`
and after :
echo “${FGBLUE} Text in blue ${NORMAL}”
echo “Text normal”
echo “${BGRED} Background in red”
echo “${BGGREEN} Background in Green and back to Normal ${NORMAL}”
Implementation example
The echo command can be implemented in the C programming language
with only a few lines of code:
#include <stdlib.h>
#include <stdio.h>
/* echo command-line arguments; 1st version */
int main(int argc, char *argv[])
{
int i;
for (i = 1; i < argc-1; i++)
{
(void) printf(“%s%s”, argv[i], ” “);
}
(void) printf(“%s%s”, argv[argc-1], “\n”);
return EXIT_SUCCESS;
}
How to list files with “dir”
The “dir” command is not new but it remains one of the most useful for average PC users. If you
have ever wanted to make a list of all the files contained in a particular folder, you will have discovered
that the Windows GUI provides no easy way to do this. It is very straightforward, however, when using
the command line. The command “dir myfolder” will list the files and folders contained in myfolder.
Again, there are switches that provide for various modifications of the command. For example “/h” will
show hidden files and “/s” will list the contents of sub-folders in addition to those of the main folder. Of
course, the normal output of the command is to the screen. To output to a file instead of the screen, the
command isdir myfolder >listmyfolder.txt where “>” is the redirection symbol. The file
“listmyfolder.txt” will be created by the command. Output can also be redirected straight to a printer on
the LPT1 port but I think it is better to first create a file and then print from there if hardcopy is desired.
These lists can be a lot longer than you might think. (These days most printers are on USB, anyway.)
This use of dir is also available in Windows 98/Me.
The dir command can also be used to list only files with a given extension. For exampledir
myfolder\*.doc /s >listmyfolder.txt will list all Microsoft Word files in myfolder and its subfolders. This
form of the command will also list all the directories and sub-directories. If you want a list of filenames
only, add the switch /b. The filename will include the full path.
Moving files
The command “move” takes a file from one folder and puts it in another. Its ability to use wild
cards makes it useful for moving all the files of a given type to another location. A command of the
typemove /y folder1\*.mp3 folder2\will move all MP3 files from folder1 to folder2. The switch ” /y” is
used if you want to prevent the system from asking if it should overwrite existing files of the same
name. To prevent overwriting, use the switch “/-y”.
Detailed Use of All Commands
Commands that we will be covering in this section:
ADDUSERS Add or list users to/from a CSV file
ARP Address Resolution Protocol
ASSOC Change file extension associations•
ASSOCIAT One step file association
ATTRIB Change file attributes
b
BCDBOOT Create or repair a system partition
BOOTCFG Edit Windows boot settings
BROWSTAT Get domain, browser and PDC info
c
CACLS Change file permissions
CALL Call one batch program from another•
CD Change Directory - move to a specific Folder•
CHANGE Change Terminal Server Session properties
CHKDSK Check Disk - check and repair disk problems
CHKNTFS Check the NTFS file system
CHOICE Accept keyboard input to a batch file
CIPHER Encrypt or Decrypt files/folders
CleanMgr Automated cleanup of Temp files, recycle bin
CLEARMEM Clear memory leaks
CLIP Copy STDIN to the Windows clipboard.
CLS Clear the screen•
CLUSTER Windows Clustering
CMD Start a new CMD shell
CMDKEY Manage stored usernames/passwords
COLOR Change colors of the CMD window•
COMP Compare the contents of two files or sets of files
COMPACT Compress files or folders on an NTFS partition
COMPRESS Compress individual files on an NTFS partition
CON2PRT Connect or disconnect a Printer
CONVERT Convert a FAT drive to NTFS.
COPY Copy one or more files to another location•
CSCcmd Client-side caching (Offline Files)
CSVDE Import or Export Active Directory data
d
DATE Display or set the date•
DEFRAG Defragment hard drive
DEL Delete one or more files•
DELPROF Delete NT user profiles
DELTREE Delete a folder and all subfolders
DevCon Device Manager Command Line Utility
DIR Display a list of files and folders•
DIRUSE Display disk usage
DISKCOMP Compare the contents of two floppy disks
DISKCOPY Copy the contents of one floppy disk to another
DISKPART Disk Administration
DNSSTAT DNS Statistics
DOSKEY Edit command line, recall commands, and create macros
DSACLs Active Directory ACLs
DSAdd Add items to active directory (user group computer)
DSGet View items in active directory (user group computer)
DSQuery Search for items in active directory (user group computer)
DSMod Modify items in active directory (user group computer)
DSMove Move an Active directory Object
DSRM Remove items from Active Directory
e
ECHO Display message on screen•
ENDLOCAL End localisation of environment changes in a batch file•
ERASE Delete one or more files•
EVENTCREATE Add a message to the Windows event log
EXIT Quit the current script/routine and set an errorlevel•
EXPAND Uncompress files
EXTRACT Uncompress CAB files
f
FC Compare two files
FIND Search for a text string in a file
FINDSTR Search for strings in files
FOR /F Loop command: against a set of files•
FOR /F Loop command: against the results of another command•
FOR Loop command: all options Files, Directory, List•
FORFILES Batch process multiple files
FORMAT Format a disk
FREEDISK Check free disk space (in bytes)
FSUTIL File and Volume utilities
FTP File Transfer Protocol
FTYPE Display or modify file types used in file extension associations•
g
GLOBAL Display membership of global groups
GOTO Direct a batch program to jump to a labelled line•
GPUPDATE Update Group Policy settings
h
HELP Online Help
i
iCACLS Change file and folder permissions
IF Conditionally perform a command•
IFMEMBER Is the current user in an NT Workgroup
IPCONFIG Configure IP
k
KILL Remove a program from memory
l
LABEL Edit a disk label
LOCAL Display membership of local groups
LOGEVENT Write text to the NT event viewer
LOGMAN Manage Performance Monitor
LOGOFF Log a user off
LOGTIME Log the date and time in a file
m
MAPISEND Send email from the command line
MBSAcli Baseline Security Analyzer.
MEM Display memory usage
MD Create new folders•
MKLINK Create a symbolic link (linkd)
MODE Configure a system device
MORE Display output, one screen at a time
MOUNTVOL Manage a volume mount point
MOVE Move files from one folder to another•
MOVEUSER Move a user from one domain to another
MSG Send a message
MSIEXEC Microsoft Windows Installer
MSINFO Windows NT diagnostics
MSTSC Terminal Server Connection (Remote Desktop Protocol)
MV Copy in-use files
n
NET Manage network resources
NETDOM Domain Manager
NETSH Configure Network Interfaces, Windows Firewall & Remote access
NETSVC Command-line Service Controller
NBTSTAT Display networking statistics (NetBIOS over TCP/IP)
NETSTAT Display networking statistics (TCP/IP)
NOW Display the current Date and Time
NSLOOKUP Name server lookup
NTBACKUP Backup folders to tape
NTRIGHTS Edit user account rights
o
OPENFILES Query or display open files
p
PATH Display or set a search path for executable files•
PATHPING Trace route plus network latency and packet loss
PAUSE Suspend processing of a batch file and display a message•
PERMS Show permissions for a user
PERFMON Performance Monitor
PING Test a network connection
POPD Restore the previous value of the current directory saved by PUSHD•
PORTQRY Display the status of ports and services
POWERCFG Configure power settings
PRINT Print a text file
PRINTBRM Print queue Backup/Recovery
PRNCNFG Display, configure or rename a printer
PRNMNGR Add, delete, list printers set the default printer
PROMPT Change the command prompt•
PsExec Execute process remotely
PsFile Show files opened remotely
PsGetSid Display the SID of a computer or a user
PsInfo List information about a system
PsKill Kill processes by name or process ID
PsList List detailed information about processes
PsLoggedOn Who’s logged on (locally or via resource sharing)
PsLogList Event log records
PsPasswd Change account password
PsService View and control services
PsShutdown Shutdown or reboot a computer
PsSuspend Suspend processes
PUSHD Save and then change the current directory•
q
QGREP Search file(s) for lines that match a given pattern.
r
RASDIAL Manage RAS connections
RASPHONE Manage RAS connections
RECOVER Recover a damaged file from a defective disk.
REG Registry: Read, Set, Export, Delete keys and values
REGEDIT Import or export registry settings
REGSVR32 Register or unregister a DLL
REGINI Change Registry Permissions
REM Record comments (remarks) in a batch file•
REN Rename a file or files•
REPLACE Replace or update one file with another
RD Delete folder(s)•
RMTSHARE Share a folder or a printer
ROBOCOPY Robust File and Folder Copy
ROUTE Manipulate network routing tables
RUN Start | RUN commands
RUNAS Execute a program under a different user account
RUNDLL32 Run a DLL command (add/remove print connections)
s
SC Service Control
SCHTASKS Schedule a command to run at a specific time
SCLIST Display NT Services
SET Display, set, or remove environment variables•
SETLOCAL Control the visibility of environment variables•
SETX Set environment variables permanently
SFC System File Checker
SHARE List or edit a file share or print share
SHIFT Shift the position of replaceable parameters in a batch file•
SHORTCUT Create a windows shortcut (.LNK file)
SHOWGRPS List the NT Workgroups a user has joined
SHOWMBRS List the Users who are members of a Workgroup
SHUTDOWN Shutdown the computer
SLEEP Wait for x seconds
SLMGR Software Licensing Management (Vista/2008)
SOON Schedule a command to run in the near future
SORT Sort input
START Start a program or command in a separate window•
SU Switch User
SUBINACL Edit file and folder Permissions, Ownership and Domain
SUBST Associate a path with a drive letter
SYSTEMINFO List system configuration
t
TASKLIST List running applications and services
TASKKILL Remove a running process from memory
TIME Display or set the system time•
TIMEOUT Delay processing of a batch file
TITLE Set the window title for a CMD.EXE session•
TLIST Task list with full path
TOUCH Change file timestamps
TRACERT Trace route to a remote host
TREE Graphical display of folder structure
TSSHUTDN Remotely shut down or reboot a terminal server
TYPE Display the contents of a text file•
TypePerf Write performance data to a log file
u
USRSTAT List domain usernames and last login
v
VER Display version information•
VERIFY Verify that files have been saved•
VOL Display a disk label•
w
WHERE Locate and display files in a directory tree
WHOAMI Output the current UserName and domain
WINDIFF Compare the contents of two files or sets of files
WINMSD Windows system diagnostics
WINMSDP Windows system diagnostics II
WINRM Windows Remote Management
WINRS Windows Remote Shell
WMIC WMI Commands
WUAUCLT Windows Update
x
XCACLS Change file and folder permissions
XCOPY Copy files and folders
:: Comment / Remark•
Filename - The comma-delimited file that AddUsers uses for data.
/s:x - Change the delimiter character used in filename to x.
an account with the same SID. This option will not erase
built-in accounts.
Password_options
/p: - Set account creation options, used along with any combination of the following:
* l - Users do not have to change passwords at next logon.
* c - Users cannot change passwords.
* e - Passwords never expire. (implies l option)
* d - Accounts disabled.
By default, all created users are required to change their password at logon.
Example
Create a comma-delimited text file, which contains the new users to be
created. Following the Syntax as follows:
[Users]
User Name,Full name, Password, Description, HomeDrive, Homepath,
Profile, Script
e.g.
[User]
jimmye,James Edward Phillip II,,,,,,
alexd,Alex Denuur,,,E:\,E:\users\alexd,,
ronj,Ron Jarook,ChangeThis,,E:\,E:\users\ronj,,
sarahs,Sarah Smith,,,,,,
u0123,Mike Olarte,,,,,,
Save the file as C:\Users.txt and execute the command
AddUsers MyDomain /c c:\Users.txt /p:e
Syntax
admodcmd [-dn BaseDN] [-p pagesize] [-s] [-server servername]
[-f LDAPFilter] [modification]
Key
-dn BaseDN Base DN to begin the LDAP query.
modification Modification to perform:
Terminal Server Attributes | Exchange Related Attributes
Mailbox Rights | User Account Settings | Custom Attributes
-p pagesize LDAP Page size to use for query.
-s Perform a subtree search
(Default = one level search)
-server servername
The server to make the changes to.
by default, changes are made locally if on a DC.
If on a member, DNS is used to find a DC.
-f LDAPFilter A Valid LDAP filter to use when enumerating objects
The default filter is (objectClass=user).
Changes made with ADModcmd can be undone, as long as the xml log
file that logged the changes still exists. These log files are typically located in
the same folder as the admodify executable.
Syntax:
admodcmd [-dn BaseDN] [-p pagesize] [-s] [-server servername]
-undo logfilename -server servername]
Key:
logfilename The log file that contains the changes to be undone.
servername The DC to write the changes to.
by default, changes are made locally if on a DC.
If on a member, DNS is used to find a DC.
ARP.exe
ARP - Address Resolution Protocol
Display and modify the IP-to-Physical address translation tables used by
address resolution protocol.
Syntax
View the contents of the local ARP cache table
ARP -a [ip_addr] [-N if_addr]
Add a static Arp entry for frequent accessed hosts
ARP -s ip_addr eth_addr [if_addr]
Delete an entry
ARP -d ip_addr [if_addr]
Key
-a Display current ARP entries.
May include more than one network interface.
If ip_addr is specified, the IP and Physical
addresses for only the specified computer are displayed.
-g Same as -a.
-N if_addr Display the ARP entries for the network interface specified
by if_addr.
-d ip_addr Delete the host specified by ip_addr.
-d * will delete all hosts.
-s Add the host and associates the Internet address ip_addr
with the Physical address eth_addr. The Physical address is
given as 6 hexadecimal bytes separated by hyphens. The entry
is permanent.
eth_addr Specifies a physical address.
if_addr If present, this specifies the Internet address of the
interface whose address translation table should be modified.
If not present, the first applicable interface will be used.
If two hosts on the same sub-net cannot ping each other successfully, try
running ARP -a to list the addresses on each computer to see if they have the
correct MAC addresses.
A host’s MAC address can be checked using IPCONFIG. If another host
with a duplicate IP address exists on the network, the ARP cache may have
had the MAC address for the other computer placed in it. ARP -d is used to
delete an entry that may be incorrect.
Examples
Display the ARP cache tables for all interfaces:
C:\> arp -a
Display the ARP cache table for the interface on IP address 10.1.4.99:
C:\> arp -a -N 10.1.4.99
Add a static ARP cache entry on IP addr 10.1.4.77 to the physical
address 00-AA-21-4A-2F-9A:
C:\> arp -s 10.1.4.77 00-AA-21-4A-2F-9A
ASSOC
Display or change the association between a file extension and a fileType
Syntax
ASSOC .ext = [fileType]
ASSOC
ASSOC .ext
ASSOC .ext =
Key
.ext : The file extension
fileType : The type of file
A file extension is the last few characters in a FileName after the period.
So a file called JANUARY.HTML has the file extension .HTML
The File extension is used by Windows NT to determine the type of
information stored in the file and therefore which application(s) will be able
to display the information in the file. File extensions are not case sensitive
and are not limited to 3 characters.
More than one file extension may be associated with the same File Type.
e.g. both the extension .JPG and the extension .JPEG may be associated
with the File Type “jpegfile”
At any one time a given file extension may only be associated with one
File Type.
e.g. If you change the extension .JPG so it is associated with the File
Type “txtfile” then it’s normal association with “jpegfile” will disappear.
Removing the association to “txtfile” does not restore the association to
“jpegfile”
File Types can be displayed in the Windows Explorer GUI: [View,
Options, File Types] however the spelling is usually different to that expected
by the ASSOC command e.g. the File Type “txtfile” is displayed in the GUI
as “Text Document”and “jpegfile” is displayed as “image/jpeg”
The command ASSOC followed by just a file extension will display the
current File Type for that extension.
ASSOC without any parameters will display all the current file
associations.
ASSOC with “.ext=” will delete the association for that file extension.
Did you leave the Always Use This Program To Open This File option
turned on?
To change it back so it prompts you to specify a program each time, just
delete the association for that file type
ASSOC .ext=
[where .ext is the file extension].
Now when you double-click on a file of that type, the system will ask
you what program you want to use.
Using the ASSOC command will edit values stored in the registry at
HKey_Classes_Root.<file extension>
Therefore it’s possible to use registry permissions to protect a file
extension and prevent any file association changes.
Examples:
Viewing file associations:
ASSOC .txt
ASSOC .doc
ASSOC >backup.txt
Editing file associations:
ASSOC .txt=txtfile
ASSOC .DIC=txtfile
ASSOC .html=Htmlfile
Deleting a file association:
ASSOC .html=
Repair .REG and .EXE file associations:
ASSOC .EXE=exefile
ASSOC .REG=regfile
Digging through CLASSES_ROOT entries often reveals more than one
shell for the same application, for example the Apple Quick Time player has
two entries, one to “open” (which gives an annoying nag screen) and one to
just “play” the QT file:
[HKEY_CLASSES_ROOT\MOVFile\shell\open] and [play]
In cases like this you can change the default action e.g.
[HKEY_CLASSES_ROOT\MOVFile\shell]
@=“play”
ASSOCIATE.exe (*)
One step file association.
This utility does the job of both ASSOC and FTYPE, in one step.
ASSOCIATE assigns an extension directly with an executable application.
This is done by automatically adding a new FileType to the system registry.
Syntax
ASSOCIATE .ext filename [/q /d /f]
Key
.ext : Extension to be associated.
filename : Executable program to associate .ext with.
/q : Quiet - Suppress interactive prompts.
/f : Force - Force overwrite or delete without questions.
/d : Delete - Delete the association.
A file extension is the last few characters in a FileName after the period.
So a file called JANUARY.HTML has the file extension .HTML
The File extension is used by Windows NT to determine the type of
information stored in the file and therefore which application(s) will be able
to display the information in the file. File extensions are not case sensitive
and are not limited to 3 characters.
Example: adding a File Association
To add the File Type “SQLfile”=Notepad.exe and also set the File
Association of .SQL=“SQLfile” run this command:
ASSOCIATE .SQL Notepad.exe
Example: Removing a File Association
ASSOCIATE .SQL /d
Note that /d will delete the File Association but will NOT delete the File
Type.
File types created by Associate.exe are always given a name in the form
xxxfile, where xxx is the file extension.
ATTRIB.exe
Display or change file attributes. Find Filenames.
Syntax
ATTRIB [ + attribute | - attribute ] [pathname] [/S [/D]]
Key
+ : Turn an attribute ON
- : Clear an attribute OFF
pathname : Drive and/or filename e.g. C:\*.txt
/S : Search the pathname including all subfolders.
/D : Process folders as well
attributes:
R Read-only (1)
H Hidden (2)
A Archive (32)
S System (4)
extended attributes:
E Encrypted
C Compressed (128:read-only)
I Not content-indexed
L Symbolic link/Junction (64:read-only)
N Normal (0: cannot be used for file selection)
O Offline
P Sparse file
T Temporary
The numeric values may be used when changing attributes with
VBS/WSH
If no attribute is specified attrib will return the current attribute settings.
Used with just the /S option ATTRIB will quickly search for a particular
filename.
Hidden and System attributes take priority.
If a file has both the Hidden and System attributes set, you can clear both
attributes only with a single ATTRIB command.
For example, to clear the Hidden and System attributes for the
RECORD.TXT file, you would type:
ATTRIB -S -H RECORD.TXT
File Attributes
You can use wildcards (? and *) with the filename parameter to display
or change the attributes for a group of files.
Remember that, if a file has the System or Hidden attribute set, you must
clear that attribute before you can change any other attributes.
Directory Attributes
You can display or change the attributes for a directory/folder. To use
ATTRIB with a directory, you must explicitly specify the directory name; you
cannot use wildcards to work with directories.
For example, to hide the directory C:\SECRET, you would type the
following:
ATTRIB +H C:\SECRET
The following command would affect only files, not directories:
ATTRIB +H C:*.*
The Read-only attribute for a folder is generally ignored by applications,
however the Read-only and System attributes are used by Windows Explorer
to determine whether the folder is a special folder, such as My Documents,
Favorites, Fonts, etc.
Setting the Read-Only attribute on a folder can affect performance,
particularly on shared drives because Windows Explorer will be forced to
request the Desktop.ini of every sub-folder to see if any special folder settings
need to be set.
Viewing archive attributes
The Archive attribute (A) is used to mark files that have changed since
they were previously backed up. The (A) flag is automatically updated by
Windows as the file is saved.
If the (A) flag is present - the file is new or has been changed since the
last backup.
The MSBACKUP, RESTORE, and XCOPY commands use these
Archive attributes, as do many (but not all) 3rd party backup solutions.
Constants - the following attribute values are returned by the
GetFileAttributes function:
FILE_ATTRIBUTE_READONLY = 1
FILE_ATTRIBUTE_HIDDEN = 2
FILE_ATTRIBUTE_SYSTEM = 4
FILE_ATTRIBUTE_DIRECTORY = 16
FILE_ATTRIBUTE_ARCHIVE = 32
FILE_ATTRIBUTE_ENCRYPTED = 64
FILE_ATTRIBUTE_NORMAL = 128
FILE_ATTRIBUTE_TEMPORARY = 256
FILE_ATTRIBUTE_SPARSE_FILE = 512
FILE_ATTRIBUTE_REPARSE_POINT = 1024
FILE_ATTRIBUTE_COMPRESSED = 2048
FILE_ATTRIBUTE_OFFLINE = 4096
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192
BCDBOOT.exe (Windows 7 /2008)
Set up a system partition, repair the boot environment located on the
system partition.
Syntax
BCDBOOT source [/l locale] [/s volume-letter]
[/v] [/m [{OS Loader GUID}]]
Options
source The location of the Windows directory to use as the source for
copying boot-environment files.
/l The locale. default = US English.
/s The volume letter of the system partition.
The default is the system partition identified by the firmware.
/v Enable verbose mode
/m By default, merge only global objects.
If an OS Loader GUID is specified, merge the given loader object within
the system template to produce a bootable entry.
BCDboot may also be run from Windows PE (Preinstallation
Environment)
Examples
Initialize the system partition using files from the operating system
image installed on the C: volume:
C:\> bcdboot C:\Windows
Set the default BCD locale to Japanese, and copy BCD (Boot
Configuration Data) files to drive S:
C:\> bcdboot C:\Windows /l ja-jp /s S:
Merge the OS loader in the current BCD store identified with the given
GUID in the new BCD store:
C:\> bcdboot c:\windows /m {d58d10c6-df53-11dc-878f-00064f4f4e08}
BOOTCFG.exe
Edit the Windows boot settings stored in Boot.ini
Syntax
BOOTCFG /addsw Add OS load options for an OS entry in boot.ini
BOOTCFG /copy Duplicate the entries for an OS instance.
BOOTCFG /dbg1394 Configure 1394 port debugging
BOOTCFG /debug Edit the debug settings for an OS.
BOOTCFG /default Specify the default OS
BOOTCFG /delete Delete an OS entry [operating systems] section of
Boot.ini
BOOTCFG /ems Redirect the EMS console to a remote computer
(server only).
(Emergency Management Services)
BOOTCFG /list List entries in boot.ini
BOOTCFG /query Display section entries from Boot.ini
BOOTCFG /raw Add OS load options, specified as a string
BOOTCFG /rebuild Totally rebuild boot.ini (use when Windows won’t
start)
BOOTCFG /rmsw Remove OS load options for an OS
BOOTCFG /timeout Change the OS time-out value.
Detailed options for all the above are available from BOOTCFG /? Items
in bold are only available from the recovery console
Default identification strings:
OS Load Options = /Fastdetect
Load Identifier = Microsoft Windows XP Professional
If you intend to rebuild the boot.ini file, delete it first - boot into the
recovery console then:
ATTRIB -H -R -S C:\Boot.ini
DEL C:\Boot.ini
Bootcfg /Rebuild
Fixboot
BROWSTAT.exe (*)
Get domain, browser and PDC info.
Syntax
BROWSTAT option
Options:
BROWSTAT Dumpnet
BROWSTAT dn : Display the transports bound to browser
BROWSTAT GetPdc Transport Domain
BROWSTAT gp Transport Domain : List the PDC name (via NetBIOS)
BROWSTAT GetMaster Transport Domain
BROWSTAT gm Transport Domain : List the remote Master Browser
name(via NetBIOS)
BROWSTAT Getblist Transport
BROWSTAT gb Transport : List the backup DNS Servers.
BROWSTAT ListWfw
BROWSTAT wfw : WindowsForWorkgroups servers running
browser.
BROWSTAT Stats \ServerName
BROWSTAT sts \ServerName : List all browser statistics
BROWSTAT Status : Display Transport,Primary DNS
BROWSTAT sta and Backup DNS servers.
BROWSTAT Status -v domain : Verbose Status Display
BROWSTAT sta -v domain include Server OS and active browsers.
BROWSTAT Tickle
BROWSTAT Tic : Force remote master to stop.
BROWSTAT Elect
BROWSTAT el : Force election on remote domain
BROWSTAT View Transport
BROWSTAT vw Transport
BROWSTAT vw Transport ‹domain›
BROWSTAT vw Transport \Server
BROWSTAT vw Transport \‹Server› /DOMAIN ‹DomainToQuery›
The VIEW options can enumerate server services running across a server
or domain. Other Browstat features will only work only within a single
network subnet. To span subnets/routers across a domain, run browstat via
psexec.
In the list displays, the following flags are used:
W = Workstation NT = Windows NT
S = Server W95 = Windows95
SQL = SQLServer WFW = WindowsForWorkgroups
SS = StandardServer MFPN= MS Netware
PDC = PrimaryDomainController NV = Novell
BDC = BackupDomainController XN = Xenix
TS = Time Source
MBC = Member Server
PQ = Print Queue Server
DL = Dial-in Server
AFP = AFP Server
OSF = OSF Server
VMS = VMS Server
PBR = Potential Browser
BBR = Backup Browser,
MBR = Master Browser
DMB = DomainMaster Browser
DFS = Distributed File System
Examples
Display transports:
C:\>browstat dn
List of transports currently bound to the browser
1 \Device\NetBT_Tcpip_{B1AFFCA2-6410-4644-9FE7-
BA6C274FD4F3}
List the backup DNS servers for transport #1:
C:\>browstat gb 1
Browser: \PC00096
Browser: \PC00082
List Print queues for transport #1:
C:\> BROWSTAT vw 1 |find “PQ”
CALL
Call one batch program from another.
Syntax
CALL [drive:][path]filename [parameters]
CALL :label [parameters]
CALL internal_cmd
Key:
pathname The batch program to run
parameters Any command-line arguments
:label Jump to a label in the current batch script.
internal_cmd Any internal command, first expanding any variables in the
argument
CALL a second batch file
The CALL command will launch a new batch file context along with any
specified arguments.
When the end of the second batch file is reached (or if EXIT is used),
control will return to just after the initial CALL statement.
CALL a subroutine (:label)
The CALL command will pass control to the statement after the label
specified along with any specified arguments .
To exit the subroutine specify GOTO:eof this will transfer control to the
end of the current subroutine.
Arguments can be passed either as a simple string or using a variable:
CALL MyScript.cmd “1234”
CALL OtherScript.cmd %_MyVariable%
Use a label to CALL a subroutine
A label is defined by a single colon followed by a name. This is the basis
of a batch file function.
CALL :s_display_result 123
ECHO Done
GOTO :eof
:s_display_result
ECHO The result is %1
GOTO :eof
At the end of the subroutine, GOTO :eof will return to the position
where you used CALL.
Example
@ECHO OFF
SETLOCAL
CALL :s_staff SMITH 100
GOTO s_last_bit
:s_staff
ECHO Name is %1
ECHO Rate is %2
GOTO :eof
:s_last_bit
ECHO The end of the script
Advanced usage : CALLing internal commands
In addition to the above, CALL can also be used to run any internal
command (SET, ECHO etc) and also expand any environment variables
passed on the same line.
For example
@ECHO off
SETLOCAL
set server1=frodo3
set server2=gandalf4
set server3=ascom5
set server4=last1
::run the Loop for each of the servers
call :loop server1
call :loop server2
call :loop server3
call :loop server4
goto:eof
:loop
set _var=%1
:: Evaluate the server name
CALL SET _result=%%%_var%%%
echo The server name is %_result%
goto :eof
:s_next_bit
:: continue below
:: Note the line shown in bold has three ‘%’ symbols
:: The CALL will expand this to: SET _result=%server1%
Each CALL does one substitution of the variables. (You can also do
CALL CALL… for multiple substitutions)
If you CALL an executable or resource kit utility make sure it’s available
on the machine where the batch will be running, also check you have the
latest versions of any resource kit utilities.
If Command Extensions are disabled, the CALL command will not
accept batch labels.
CD
Change Directory - Select a Folder (and drive)
Syntax
CD [/D] [drive:][path]
CD [..]
Key
/D : change the current DRIVE in addition to changing folder.
Examples
To change to the parent directory.
C:\Work> CD ..
To change to the grant-parent directory.
C:\Work\backup\January> CD ....
To change to the ROOT directory.
C:\Work\backup\January> CD \
To display the current directory in the specified drive.
C:\> CD D:
To display the current drive and directory.
C:\Work> CD
To display the current drive and directory.
C:\Work> ECHO “%CD%”
In a batch file to display the location of the batch script file (%0)
C:\> ECHO “%~dp0”
Moving down the folder tree with a full path reference to the ROOT
folder…
C:\windows> CD \windows\java
C:\windows\java>
Moving down the folder tree with a reference RELATIVE to the current
folder…
C:\windows> CD java
C:\windows\java>
Moving up and down the folder tree in one command…
C:\windows\java> CD ..\system32
C:\windows\system32>
If Command Extensions are enabled the CD command is enhanced as
follows:
1) The current directory string is converted to use the correct CASE.
So CD C:\wiNnt would actually set the current directory to C:\Winnt
2) CD does not treat spaces as delimiters, so it is possible to CD into a
subfolder name that contains a space without surrounding the name with
quotes.
For example:
cd \My folder
is the same as:
cd “\My folder”
3) An asterisk can be used to complete a folder name
e.g. from C:\
C:> CD pro*
will move to
C:\Program Files
CHDIR is a synonym for CD
Tab Completion
This allows changing current folder by entering part of the path and
pressing TAB
C:> CD Prog [PRESS TAB]
Will go to C:\Program Files\
Tab Completion is disabled by default, it has been known to create
difficulty when using a batch script to process text files that contain TAB
characters.
Tab Completion is turned on by setting the registry value shown below
REGEDIT4
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
“CompletionChar”=dword:00000009
Changing the Current drive
simply enter the drive letter followed by a colon
C:> E:
E:>
To change drive and directory at the same time, use CD with the /D
switch
C:> cd /D E:\utils
E:\utils\>
CHANGE
Change Terminal Server Session properties, use when installing software
on a terminal server.
Syntax
CHANGE USER /options
CHANGE LOGON /options
CHANGE PORT /options
Options:
To change .INI file mapping: (administrator rights required)
CHANGE USER /INSTALL Enable install mode. This command has
to be run before
installing any new software on a Terminal Server.
This will create a .ini file for the application
in the TS system directory.
CHANGE USER /EXECUTE Enable execute mode (default)
Run this when an installation is complete.
CHANGE USER /QUERY Display current settings.
To enable or disable terminal session logins:
CHANGE LOGON /QUERY Query current terminal session login
mode.
CHANGE LOGON /ENABLE Enable user login from terminal
sessions.
CHANGE LOGON /DISABLE Disable user login from terminal
sessions.
To list or change COM port mappings for the current session.
This can allow DOS applications to access high numbered ports e.g.
COM12
CHANGE PORT portx=porty Map port x to port y.
CHANGE PORT /D portx Delete mapping for port x.
CHANGE PORT /QUERY Display current mapping ports.
How .ini files work:
Installing an application will create a .ini file in the TS system directory.
The first time a user runs the application, the application looks in the
home directory for its .ini file. If none is found then Terminal Server will
copy the .ini file from the system directory to the users home directory.
Each user will have a unique copy of the application’s .ini file in their
home directory.
To learn more about what happens when the system is put into install
mode run CHANGE USER /?
The CHANGE command replaces CHGLOGON, CHGUSER, and
CHGPORT from Citrix Winframe.
chkdsk.exe
Check Disk - check and repair disk problems
Syntax
CHKDSK [drive:][[path]filename] [/F] [/V] [/R] [/L[:size]]
Key
[drive:] The drive to check.
filename File(s) to check for fragmentation (FAT only).
/F Automatically Fix file system errors on the disk.
/X Fix file system errors on the disk, (Win2003 and above)
dismounts the volume first, closing all open file handles.
/R Scan for and attempt Recovery of bad sectors.
/V Display the full path and name of every file on the disk.
/L:size NTFS only: change the log file size to the specified number of
kilobytes.
If size is not specified, displays the current log size and the drive type
(FAT or NTFS).
/C Skip directory corruption checks.
/I Skip corruption checks that compare directory entries to the
file record segment (FRS) in the volume’s master file table (MFT)
Example:
CHKDSK C: /F
Fixing Errors /F
If the drive is the boot partition, you will be prompted to run the check
during the next boot
If you specify the /f switch, chkdsk will show an error if open files are
found on the disk.
Chkdsk /f will lock the volume, making data unavailable until chkdsk is
finished.
If you use chkdsk /f on a disk with a very large number of files
(millions), chkdsk may take a long time to complete.
When you delete a file or folder that has ‘custom’ permissions, the ACL
is not deleted, it is cached. Chkdsk /f will remove ACLs that are no longer
used. This is often the cause of the rather worrying message: “Windows found
problems with the file system. Run chkdsk with the /F (fix) option to correct
these.”
It is normal for chkdsk /F to remove unused index entries and unused
security descriptors every time you run it, these do not indicate a problem
with the file system.
Scan only (without /f switch)
If a file needs to be fixed chkdsk will alert you with a message but will
not fix the error(s).
chkdsk may report lost allocation units on the disk - it will produce this
report even if the files are in-use (open). If corruption is found, consider
closing all files and repairing the disk with /F.
Running chkdsk on a data volume that is in use by another program or
process may incorrectly report errors when none are present. To avoid this,
close all programs or processes that have open handles to the volume.
On computers running Windows 2003 SP1, chkdsk automatically creates
a shadow copy, so you can check volumes that are ‘in use’ by another
program or process. This enables an accurate report against a live file server.
On earlier versions of Windows, chkdsk would always lock the volume,
making data unavailable.
Run at Bootup
Running at bootup is often the easiest way to close all open file handles.
Use the GUI, chkntfs or the FSUTIL dirty commands to set or query the
volumes ‘dirty’ bit so that Windows will run chkdsk when the computer is
restarted.
Event Logs
Chkdsk will log error messages in the Event Viewer - System Log.
Chkdsk /f removes ACLs that are no longer used and reports this in the
Event Viewer - Application Log.
Cluster (or block) Size
CHKDSK produces a report that shows the the block /cluster size
typically: “4096 bytes in each allocation unit.”
When the cluster size is greater than 4 KB on an NTFS volume, none of
the NTFS compression functions are available.
Exit codes
0 No errors were found
1 Errors were found and fixed.
2 Could not check the disk, did not or could not fix errors.
Notes:
Consider the time required to run Chkdsk to repair any errors that occur.
Chkdsk times are determined by the number of files on the volume and by the
number of files in the largest folder. Chkdsk performance was improved by
30% under Windows 2003 and around 50% in 2008 R2.
To issue chkdsk on a hard drive you must be a member of the
Administrators group.
When CHKDSK is set to run at boot-up there is a delay to allow the
check to be cancelled - this can be configured in the registry:
HKLM\System\CurrentControlSet\Control\Session Manager
REG_DWORD:AutoChkTimeOutData
The value is the time in seconds that you want CHKDSK to wait (0 = no
delay) default is 10 seconds.
Chkdsk is also available from the Recovery Console (with different
parameters.)
Disk Errors
“The file system structure on the disk is corrupt and unusable”
If you have disk corruption, run the drive manufacturers diagnostics:
Toshiba | Hitachi | ibm | Seagate/Maxtor/Freeagent | Western digital
CHKNTFS.exe
Check the NTFS file system with CHKDSK
Syntax
CHKNTFS drive: […]
CHKNTFS /C drive: […]
CHKNTFS /X drive: […]
CHKNTFS /t[:Time]
CHKNTFS /D
Key
drive : Specifies a drive letter.
/C : Check - schedules chkdsk to be run at the next reboot.
/X : Exclude a drive from the default boot-time check.
Excluded drives are not accumulated between command invocations.
/T : Change the Autochk.exe initiation countdown time (time in seconds)
If you don’t specify Time: displays the current countdown time.
/D : Restore the machine to the default behavior; all drives are
checked at boot time and chkdsk is run on those that are dirty.
This undoes the effect of the /X option.
If no switches are specified, CHKNTFS will display the status of the
dirty bit for each drive.
/T option is new in Win XP
CHOICE.exe
Accept user input to a batch file. Choice allows single key-presses to be
captured from the keyboard.
CHOICE [/c [choiceKeys]] [/N] [/CS] [/t Timeout /d Choice] [/m Text]
key
/C[:]choiceKeys : One or more keys the user can press. Default is YN.
/N : Do not display choiceKeys at the end of the prompt string.
/CS : Make the choiceKeys Case Sensitive.
/T Timeout : Timeout in Timeout seconds
If Timeout is 0 there will be no pause and the
default will be selected.
/d choice : Default choice made on Timeout.
/m text : Message string to describe the choices available.
ERRORLEVEL will return the numerical offset of choiceKeys.
Choice.exe is a standard command in Windows 2003, Vista and
Windows 7 (for XP you can use the early resource kit versions).
Bugs
Early versions of Choice.com (not Choice.exe) burn a lot of CPU’s when
in a wait state, plus there are some issues where multiple concurrent
invocations will clobber each other.
Examples:
CHOICE /C CH /M Select [C] CD or [H] Hard drive
IF errorlevel 2 goto sub_hard
IF errorlevel 1 goto sub_cd
The order of the IF statements above matters, IF errorlevel 1 will return
TRUE for an errorlevel of 2
CHOICE can be used to set a specific %errorlevel%
for example to set the %errorlevel% to 6 :
ECHO 6| CHOICE /C 123456 /N >NUL
CIPHER
Encrypt or Decrypt files and folders.
Without parameters cipher will display the encryption state of the current
folder and files.
NTFS volumes only.
Syntax:
Encrypt/Decrypt:
CIPHER [{/e | /d}] [/s:Folder] [options] [/u[/n]] [{PathName […]]
New recovery agent certificate:
CIPHER /r:PathNameWithoutExtension
Remove data:
CIPHER /w:PathName
Backup Keys:
CIPHER /x[:PathName]
options:
/e Encrypt the folders.
Folders are marked so that files that are added to the folder later
are encrypted too.
/d Decrypt the folders.
Folders are marked so that files that are added to the folder later
are encrypted too.
/s:Folder
Performs the operation in the folder and all subfolders.
/a Perform the operation for files and directories.
/i Continue even after errors occur.
By default, cipher stops when it encounters an error.
/f Force the encryption or decryption of all specified objects.
By default, cipher skips files that have been encrypted or decrypted already.
/q Quiet - Report only essential information.
/h Display files with hidden or system attributes.
By default, these files are not encrypted or decrypted.
/k Create a new file encryption key for the user running cipher.
/u Update the user’s file encryption key or recovery agent’s key
to the current ones in all of the encrypted files on local drives
(that is, if the keys have been changed).
This option only works with /n.
/n Prevent keys from being updated.
Use this option to find all of the encrypted files on the local drives.
This option only works with /u.
PathName
A pattern, file, or folder.
/r:PathNameWithoutExtension
Generate a new recovery agent certificate and private key, and
then write them to files with the filename PathNameWithoutExtension.
/w:PathName
Remove data from unused portions of a volume.
PathName can indicate any directory on the desired volume.
Cipher does not obtain an exclusive lock on the drive.
This option can take a long time to complete and should only be used when
necessary.
/x[:PathName] PathNameWithoutExtension
Identifies the certificates and private keys used by EFS for the
currently logged on user and backs them up to a file.
If PathName is provided, the certificate used to encrypt the files
is backed up. Otherwise, the user’s current EFS certificate and keys
will be backed up.
The certificates and private keys are written to a file name
PathNameWithoutExtension plus the file extension .pfx.
Notes
It is recommended that you always encrypt both the file and the folder in
which it resides, this prevents an encrypted file from becoming decrypted
when it is modified.
Cipher cannot encrypt files that are marked as read-only.
Cipher will accept multiple folder names and wildcard characters. You
must separate multiple parameters with at least one space.
Examples
List encrypted files in the reports folder are:
CIPHER c:\reports\*
Encrypt the Reports folder and all subfolders:
CIPHER /e /s:C:\reports
To back up the certificate and private key currently used to encrypt and
decrypt EFS files to a file named c:\myefsbackup.pfx, type:
CIPHER /x c:\myefsbackup
CLEANMGR.exe
Automated cleanup of Temp files, Internet files, downloaded files,
recycle bin (XP).
Syntax
CLEANMGR option
Options
/d driveletter: - Select the drive that you want Disk Cleanup to clean.
/sageset:n - Display the Disk Cleanup Settings dialog box and create
a registry key to store the settings you select.
The n value is stored in the registry and allows you to
specify different tasks for Disk Cleanup to run.
n can be any integer from 0 to 65535.
Specify the %systemroot% drive to see all the available options.
/sagerun:n - Run task ‘n’
All drives in the computer will be enumerated, and the
selected profile will be run against each drive.
Only one of the 3 options above can be run at a time
Examples
CLEANMGR /sageset:64
CLEANMGR /sagerun:64
Options that can be chosen for cleanup:
Temporary Internet Files
Temporary Setup Files
Downloaded Program Files
Old Chkdsk Files
Recycle Bin
Temporary Files
Temporary Offline Files
Offline Files
Compress Old Files
Catalog Files for the Content Indexer
Items in bold may appear in more than one drive i.e not just in
%SystemRoot%
If you want to choose the options automatically, without any user
interaction then run a registry script like this
e.g.
REGEDIT /S cleanmgr.reg
CLEANMGR /sagerun:64
Other items you may want to clear out…
Application Data
Most files in Application Data are things like browser bookmark files - best
left alone.
However some applications (e.g. MS Access) leave large files in
application data which you probably don’t need in a roaming profile, these
can be selectively deleted with a batch script like this.
Recent files
To clear the shortcuts for Start, Documents
cd %userprofile%\Recent
echo y| del *.*
Notice that the ‘Recent’ folder may contain many more shortcuts than
are set to display under Start, Documents.
Locked files (Typically IE temp files or the Offline cache)
This works on any version of NT, 2000 or XP
Close all applications
Open a command prompt
Click Start, and then Shut Down
Simultaneously press CTRL+SHIFT+ALT.
While you keep these keys pressed, click Cancel in the Shut Down
Windows dialog box.
In the command prompt window, navigate to the cache location, and delete
all files from the folder (DEL /s)
At the command prompt, type explorer, and then press ENTER.
CLIP.exe (Resource Kit / Windows 7)
Copy the result of any command to the Windows clipboard.
Syntax
command | CLIP
CLIP < filename.txt
When using clip in a batch script you should warn the user that their
clipboard is about to be overwritten.
For Example:
DIR | CLIP
DATE /t | CLIP
CMD.exe
Start a new CMD shell.
Syntax
CMD [charset] [options] [My_Command]
Options
/C Carries out My_Command and then terminates
/K Carries out My_Command but remains
My_Command : The command, program or batch script to be run.
This can even be several commands separated with ‘&’
(the whole should also be surrounded by “quotes”)
/T:fg Sets the foreground/background colours
/X Enable extensions to CMD.EXE
under Windows 2000 you can also use /E:ON
/Y Disable extensions to CMD.EXE
under Windows 2000 you can also use /E:OFF
/A Output ANSI Characters
/U Output UNICODE Characters
These 2 swiches are useful when piping or redirecting to a file
Most common text files under WinNT are ANSI, use these switches
when you need to convert the character set.
/D Ignore registry AutoRun commands
HKLM | HKCU \Software\Microsoft\Command Processor\AutoRun
/F:ON Enable auto-completion of pathnames entered at the CMD prompt
/F:OFF Disable auto-completion of pathnames entered at the CMD prompt
(default)
At the command prompt Ctrl-D gives folder name completion and Ctrl-F
gives File and folder name completion.
These key-strokes will display the first matching path. Thereafter, repeated
pressing of the same control key will cycle through the list of matching paths.
Pressing SHIFT with the control key will move through the list backwards.
/Q Turn echo off
/S Strip quote characters from the command_line
/V:ON Enable delayed environment variable expansion
this allows a FOR loop to specify !variable! instead of %variable%
expanding the variable at execution time instead of at input time.
/V:OFF Disable delayed environment expansion.
Environment expansion preference can be set permanently in the registry
HKLM | HKCU \Software\Microsoft\Command
Processor\DelayedExpansion
Set to either 0x1 or 0x0
/knetdiag /debug
/knetdiag /fix
The knetdiag switches are undocumented and work in XP only
they list and (may) fix these networking issues.
If /C or /K is specified, then the remainder of the command line is
processed as an immediate command in the new shell. Multiple
commands
separated by the command separator ‘&&’ are accepted if surrounded by
quotes.
The following logic is used to process quote (“) characters:
1. If all of the following conditions are met, then quote characters
on the command line are preserved:
- no /S switch
- exactly two quote characters
- no special characters between the two quote characters,
where special is one of: &<>()@^|
- there are one or more whitespace characters between the
the two quote characters
- the string between the two quote characters is the name
of an executable file.
2. Otherwise, old behavior is to see if the first character is
a quote character and if so, strip the leading character and
remove the last quote character on the command line, preserving
any text after the last quote character.
Command.com vs cmd.exe
All the commands on these pages assume you are running the 32 bit or
64 bit command line (cmd.exe)
The old 16 bit command processor command.com is supplied to provide
backward compatibility for 16 bit DOS applications. Command.com has very
limited functionality compared to cmd.exe e.g. it will fail to set an
%errorlevel% after many commands.
If you name your batch scripts with the extension .CMD rather than
.BAT then they will not run under command.com even if copied to a Windows
95 machine.
The %COMSPEC% environment variable will show if you are running
CMD.EXE or command.com
On 64 bit versions of windows the 32 bit CMD.exe can be found at
%windir%\SysWoW64\cmd.exe To reduce compatibility issues, the WOW64
subsystem isolates 32-bit binaries from 64-bit binaries by redirecting registry
calls and some file system calls.
Opening CMD from Windows Explorer
You can open a new CMD prompt by choosing START, RUN, cmd, OK
Registry Keys for CMD:
;Allow UNC paths at command prompt
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command
Processor]
“DisableUNCCheck”=dword:00000001
; Run a command when CMD.exe starts
[HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor]
“AutoRun”=-
; Activate Automatic Completion
[HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor]
“CompletionChar”=0x9
; For Windows 7: Add an elevated ‘Open CMD prompt here (Admin)’
option to the
; context menu for file system folders:
[HKEY_CLASSES_ROOT\Directory\shell\runas]
@=“Open CMD prompt here (Admin)”
[HKEY_CLASSES_ROOT\Directory\shell\runas\command]
@=“cmd.exe /k pushd %L”
; For Windows 7: Add an elevated ‘Open CMD prompt here (Admin)’
option to the
; My Computer context menu:
[HKEY_CLASSES_ROOT\CLSID\{20D04FE0-3AEA-1069-A2D8-
08002B30309D}\shell\runas]
@=“Open CMD prompt here (Admin)”
[HKEY_CLASSES_ROOT\CLSID\{20D04FE0-3AEA-1069-A2D8-
08002B30309D}\shell\runas\command]
@=“cmd.exe”
Previous Commands
Pressing the UP arrow will list previous commands entered at the
command prompt.
Other DOSKEY function keys are loaded by default (F7, F8, F9)
Copy and Paste / QuickEdit
To simplify the use of cut and paste at the Command Prompt, enable
QuickEdit mode as follows:
Activate the control menu at the top left of the current cmd window, go
to Properties, Options tab and then tick against QuickEdit Mode.
Now you can select text with the mouse and hit Enter (or right click) to
copy it to the clipboard. Paste anywhere using Control+V (or Right Click) or
via the menu.
ESC will cancel any selection and return to editing mode.
When copying between windows, you may need one click to select the
window and a second click to paste.
Run multiple instances of CMD.exe
At the command line or in a batch script CMD will start a new instance
of CMD.exe which will appear in the same window. The EXIT command will
close the second CMD instance and return to the previous shell.
A method of calling one Batch script from another is to run a command
like CMD /c C:\docs\myscript.cmd
The output of CMD can be redirected into a text file. Notice that where
CMD /c is used, the EXIT command is not required.
The environment Variable %CMDCMDLINE% will expand into the
original command line passed to CMD.EXE
The native version of CMD.exe is always in %windir%\system32, on 64
bit operating systems there is also a 32 bit CMD.exe in
%windir%\SysWOW64
Pausing or stopping a batch script
Execution of any batch script can be paused by pressing CTRL-S
This also works for pausing a single command such as a DIR listing
Pressing any key will resume the operation.
Execution of any batch script can be stopped by pressing CTRL-C
If one batch file CALLs another batch file CTRL-C will exit both batch
scripts.
If CMD /c is used to call one batch file from another then CTRL-C will
cause only one of the batch scripts to terminate. (see also EXIT)
Long Commands and long filenames
Under Windows XP, the CMD command line is limited to 8,191
characters.
For all versions of Windows, NTFS and FAT allows pathnames of up to
260 characters.
A workaround for the limited pathname length is to prefix \?\
for example:
\?\C:\TEMP\Long_Directory\Long_Filename.txt
ErrorLevel
CMD /C will return an errorlevel, for example CMD /c dir Z: where the
drive Z: does not exist, will return %errorlevel% = 1 to the calling CMD
shell.
Full Screen
The key combination ALT + ENTER will switch a CMD window to full
screen mode.
press ALT and ENTER again to return to a normal Window.
Command Extensions
Much of the functionality of CMD.exe can be disabled - this will affect
all the internal commands, Command Extensions are enabled by default. This
is controlled by setting a value in the registry:
HKCU\Software\Microsoft\Command Processor\EnableExtensions
Alternatively under Win XP you can run CMD /e:on or CMD /e:off
CMDKEY.exe (Windows 7)
Create, list or delete stored user names, passwords or credentials.
Syntax
cmdkey [{/add:TargetName|/generic:TargetName}]
{/smartcard|/user:UserName [/pass:Password]}
[/delete{:TargetName|/ras}]
/list:TargetName
Key:
/add Add a user name and password to the list.
TargetName The computer or domain name that this entry will be
associated with.
/generic Add generic credentials to the list.
/smartcard Retrieve the credential from a smart card.
/user:UserName The user or account name to store with this entry.
If UserName is not supplied, it will be requested.
/pass:Password The password to store with this entry. If Password is not
supplied, it will be requested.
/delete: Delete a user name and password from the list.
If TargetName is specified, that entry will be deleted.
If /ras is specified, the stored remote access entry will be deleted.
/list Display the list of stored user names and credentials.
If TargetName is not specified, all stored user names and credentials will be
listed.
If more than one smart card is found, cmdkey will prompt the user to
specify which one to use.
Once stored, passwords are not displayed.
Examples:
Display a list of stored user names and credentials:
cmdkey /list
Add a user name and password for user Kate to access computer
Server01 with the password passme, type:
cmdkey /add:server01 /user:Kate /pass:passme
Add a user name for user Kate to access computer Server01 and prompt
for the password whenever Server01 is accessed:
cmdkey /add:server01 /user:Kate
Delete the stored credential for remote access:
cmdkey /delete /ras
Delete the stored credential for Server01:
cmdkey /delete:Server01
COLOR
(Note – Command is “Color” regardless of language/locale settings)
Sets the default console foreground and background colours.
Syntax
COLOR [background][foreground]
Colour attributes are specified by 2 of the following hex digits. Each
digit can be any of the following values:
0 = Black
8 = Gray
1 = Blue
9 = Light Blue
2 = Green
A = Light Green
3 = Aqua
B = Light Aqua
4 = Red
C = Light Red
5 = Purple
D = Light Purple
6 = Yellow
E = Light Yellow
7 = White
F = Bright White
If no argument is given, COLOR restores the colour to what it was when
CMD.EXE started.
Colour values are assigned in the following order:
The DefaultColor registry value.
The CMD /T command line switch
The current colour settings when cmd was launched
The COLOR command sets ERRORLEVEL to 1 if an attempt is made to
execute the COLOR command with a foreground and background colour that
are the same.
COLOR 07, white on black is the default.
“COLOR 00” is an invalid option and will set %ERRORLEVEL% to 1
The COLOR command will change the color of all the text in the
window.
COMP.exe
Compare two files (or sets of files). Display items which do not match.
Syntax
COMP [pathname1] [pathname2] [/D] [/A] [/L] [/N=number] [/C]
Key
pathname1 The path and filename of the first file(s)
pathname2 The path and filename of the second file(s)
/D Display differences in decimal format. (default)
/A Display differences in ASCII characters.
/L Display line numbers for differences.
/N=number Compare only the first X number of lines in the file.
/C do a case insensitive string comparison
Running COMP with no parameters will result in a prompt for the 2 files
and any options
To compare sets of files, use wildcards in pathname1 and pathname2
parameters.
When used with the /A option COMP is similar to the FC command but
it displays the individual characters that differ between the files rather than
the whole line.
To compare files of different sizes, use /N= to compare only the first n
lines (common portion of each file.)
COMP will normally finish with a Compare more files (Y/N) prompt
to suppress this: ECHO n|COMP <options>
CON2PRT.exe (Zero Admin Kit)
Connect or disconnect a Printer
All commands issued using this utility will affect only the user currently
logged in. Con2prt is therefore ideal for managing NETWORK printer
connections when used in a login script.
Syntax
CON2PRT /f
CON2PRT /c \PrintServer\PrintShare
CON2PRT /cd \PrintServer\PrintShare
Key
/f - remove all network printer connections
/c - connect to \PrintServer\PrintShare
/cd - connect to and set PrintShare as the default printer
Several switches can be combined in one command line. So you can
remove all connections before adding new ones all in one command, you can
only specify one default printer.
For recent versions of Windows Microsoft now recommend the more
flexible RUNDLL32 in preference to con2prt.
The freeware utility AdPrintX is very similar to Con2Prt but has
additional functionality, including compatibility with Windows 9x systems.
COPY
Copy one or more files to another location
Syntax
COPY source destination [options]
COPY source1 + source2.. destination [options]
Key
source : Pathname for the file or files to be copied.
/A : ASCII text file (default)
/B : Binary file copy - will copy extended characters.
destination : Pathname for the new file(s).
/V : Verify that the new files were written correctly.
/N : If at all possible, use only a short filename (8.3) when creating
a destination file. This may be necessary when copying between disks
that are formatted differently e.g NTFS and VFAT, or when archiving
data to an ISO9660 CDROM.
/Z : Copy files in restartable mode. If the copy is interrupted
part way through, it will restart if possible. (use on slow networks)
/Y : Suppress confirmation prompt (Windows 2000 only)
/-Y : Enable confirmation prompt (Windows 2000 only)
Prompt to overwrite destination file
NT 4 will overwrite destination files without any prompt, Windows 2000
and above will prompt unless the COPY command is being executed from
within a batch script.
To force the overwriting of destination files under both NT4 and
Windows2000 use the COPYCMD environment variable:
SET COPYCMD=/Y
This will turn off the prompt in Win2000 and will be ignored by NT4
(which overwrites by default)
Binary copies
“COPY /B … ” will copy all the files in binary mode , you can also put
/B after any one file to copy just that file in binary.
Combine files
To combine files, specify a single file for the destination, but multiple
files as the source. To specify more than one file use wildcards or list the files
with a + in between each (file1+file2+file3)
When copying multiple files in this way the first file must exist or else
the copy will fail, a workaround for this is COPY null + file1 + file2 dest1
COPY will accept UNC pathnames
Copy from the console (accept user input)
COPY CON filename.txt
Then type the input text followed by ^Z (Control key & Z)
To do this in Powershell use the following function:
function copycon {
[system.console]::in.readtoend()
}
Examples:
In the current folder
COPY oldfile.doc newfile.doc
Copy from a different folder/directory:
COPY “C:\my work\some file.doc” “D:\New docs\newfile.doc”
Specify the source only, with a wildcard will copy all the files into the
current directory:
COPY “C:\my work\*.doc”
Specify the source with a wildcard and the destination as a single file,
this is generally only useful with plain text files.
COPY “C:\my work\*.txt” “D:\New docs\combined.txt”
Quiet copy (no feedback on screen)
COPY oldfile.doc newfile.doc >nul
CSCcmd (Client-side caching command (Q884739 - Non Microsoft
mirror)
Run this utility on a client PC to configure offline files. Offline files
(CSC) allow the client PC to access copies of network files while
disconnected from the network/domain. Files can be synchronized with the
network when connected.
Syntax
CSCCMD Option(s)
Options:
/ENABLE Enable Client-Side Caching (CSC) on this client.
Requires Local Administrator rights
/DISABLE Disable CSC, ensure all offline files are closed first.
/Enum[: \Server\Share [\Path]] [/RECURSE]
Display all the shares in the local cache.
With the /RECURSE option, this will display the contents
of the shares within a parent share.
/DISCONNECT:\Server
/DISCONNECT:\Server\Share
Disconnect a server or share from CSC on this client.
/MOVESHARE:\Server1\Share \Server2\Share
Move files and folders from one share to another in the cache.
This is useful if the local cache must point to a new/renamed server
location.
/RESID Restamp all the entries in the Windows offline files (CSC)
database
with a new user security identifier (SID).
useful when moving user accounts from an NT 4.0 domain to 2003.
/ISENABLED Is CSC is enabled on this client PC. (synonym:
/ISCSCENABLED)
/PIN2:\server\share\path [/USER] [/SYSTEM] [/USERINHERIT]
[/SYSTEMINHERIT]
Pin shared resources:
Use the PIN2: /USER option to pin a file. This has the same result
as using the Offline Files dialog box to cache the file.
Use PIN2: /SYSTEM to specify that the share will be pinned via Group
Policy.
/USERINHERIT and /SYSTEMINHERIT] will determine how the pin data
is inherited.
/PIN2:filename /FILELIST [/UNICODE] [/USER] [/SYSTEM]
[/USERINHERIT] [/SYSTEMINHERIT]
Use a file to describe the objects to pin
The file contains the UNC path of each object to pin.
/FILELIST = the objects are separated by a carriage return/linefeed.
/UNPIN2:\server\share\path [/USER] [/SYSTEM] [/USERINHERIT]
[/SYSTEMINHERIT] [/RECURSE]
UnPin a shared resource or remove a shared resource from the local cache.
with /RECURSE, CSCCMD will unpin all children of the path.
with /RECURSE2, CSCCMD will unpin the path and children of the path.
/UNPIN2:filename /FILELIST [/UNICODE] [/USER] [/SYSTEM]
[/USERINHERIT] [/SYSTEMINHERIT]
UnPin specific shared resources listed in filename.
/FILELIST = the objects are separated by a carriage return/linefeed.
/FILL:\Server\Share\Path
Copy server-side data to the local cache.
/FILL:FileName /FILELIST [/UNICODE]
Copy server-side data to the local cache using a file.
/DELETE:\Server\Share\Path [/RECURSE] [/RECURSE2]
Delete a file, a directory, or a share from the local cache.
Ensure that the directory/share is empty before you use this switch.
with /RECURSE, CSCCMD tool only operates on the children of the path.
with /RECURSE2, CSCCMD operates on the path and children of the path.
/ISSERVEROFFLINE:\Server
Does CSC consider \server to be offline.
To get a reliable response from this switch, you must first open a
share/file/directory from the local cache for \server
/SETSPACE:Bytes
Specify the disk space in bytes to allocate to temporary offline files.
These files are nonpinned, auto-cached files.
This is similar to the function provided in the Offline Files dialog box.
/CHECKDB [/QUICK]
Examine the CSC database and display any database error flags.
/QUICK will skip the enumeration and just display database errors.
/EXTRACT[:\Server\Share[\Path]] /TARGET:Path [/RECURSE]
[/ONLYMODIFIED] [/STOPONERROR]
Extract a file, a directory, or a directory tree from the local cache.
This requires Local Administrator permissions
/TARGET will specify a destination.(which need not already exist)
/ONLYMODIFIED, extract only files that have been modified offline.
/STOPONERROR, stop the extract if an error occurs.
Offline files are most often used with laptops to provide access to data
when on the move. Folder redirection can be setup to place the users My
Documents on a server share, and then Offline Files can be set to copy and
cache the data to the laptops C: drive.
This arrangement allows faster synchronisation of files than a full
roaming profile (which also synchronises other things you probably don’t
need on a laptop.)
The /PIN2 switch does not copy the content of the shared resource into
the local cache. Pinning is not sufficient to make the files available offline.
After you use the /PIN2 switch, you must run CSCCMD /FILL to copy the
content of the shared resource to the local cache.
When using FILELIST, any white space at the start of a file is ignored.
With the /UNICODE option, CSCCMD will create or read a file list in
Unicode text format.
CSC is available for Windows 2000/XP/2003.
Examples
Move a server share:
csccmd /MOVESHARE:\oldserver\share \newserver\share
csccmd /RESID
CSVDE / LDIFDE (Directory Exchange)
Import or Export Active Directory data to a file. The syntax of these two
commands is identical, the difference being that one works with CSV files
and one with LDIF files.
Syntax
Export to file:
CSVDE [-f FileName] [options]
LDIFDE [-f FileName] [options]
Import from File:
CSVDE -i [-f FileName] [options]
LDIFDE -i [-f FileName] [options]
Key
-f Filename Input or Output filename
-s servername The server to bind to
-c FromDN ToDN Replace occurrences of FromDN to ToDN
-v Verbose
-j Path Folder to store log files
-t Port_Number (default = 389)
-? Help
Export options
-d RootDN The root of the LDAP search (Default to Naming Context)
-r Filter LDAP search filter (Default to “(objectClass=*)”)
-p SearchScope Search Scope (Base/OneLevel/Subtree)
-l list Attributes to look for in an LDAP search
(comma separated List)
-o list Attributes to omit from input
(comma separated list)
-g Disable Paged Search
-m Enable the SAM logic on export
-n Do not export binary values
Import options
-k Ignore ‘Constraint Violation’ and ‘Object Already Exists’ errors.
Note to successfully import a file it must contain as a minimum
The DN(distinguished name), DisplayName and ObjectClass
Username/Password credentials
-a Sets the command to run using the supplied user distinguished name
and password. For example: “cn=yourname,dc=yourcompany,dc-com
password”
-b Sets the command to run as username domain password. The default
is
to run using the credentials of the currently logged on user.
CSV (comma-separated value) format files can be read with MS Excel
and are easily modified with a batch script.
LDIF files (Ldap Data Interchange Format) are a cross-platform
standard. This provides a method to populate Active Directory with data from
other directory services. (e.g. Netscape NDS, Novell NDS/eDirectory, Oracle
Internet Directory)
Passwords
For security reasons neither of these tools will export passwords. When
you import an account it is given a null password, if the domain has a
password length policy, then the account will be disabled (You can re-enable
accounts in bulk with a script)
Compatibility
CSVDE and LDIFDE are supplied with Windows 2000/2003 Server but
can also be run on Win2000 Professional and XP Professional (i.e run
remotely against the Active Directory Server.)
Examples
Export the whole domain
CSVDE -f MyDomain.csv
Export all users with a particular surname:
CSVDE -f MyUsers.csv -r (and(objectClass=User)(sn=Surname))
Import the whole domain and create C:\MyLogfiles\csv.log and
C:\MyLogfiles\csv.err
CSVDE -i -f MyDomain.csv -j C:\MyLogfiles\
CACLS.exe
Display or modify Access Control Lists (ACLs) for files and folders.
Access Control Lists apply only to files stored on an NTFS formatted
drive, each ACL determines which users (or groups of users) can read or edit
the file. When a new file is created it normally inherits ACL’s from the folder
where it was created.
Syntax
CACLS pathname [options]
Options:
/T Search the pathname including all subfolders.
/E Edit ACL (leave existing rights unchanged)
/C Continue on access denied errors.
/G user:permission
Grant access rights, permision can be:
R Read
W Write
C Change (read/write)
F Full control
/R user
Revoke specified user’s access rights (only valid with /E).
/P user:permission
Replace access rights, permission can be:
N None
R Read
W Write
C Change (read/write)
F Full control
/D user
Deny access to user.
In all the options above “user” can be a UserName or a Workgroup
(either local or global)
You can specify more than one user:permission in a single command.
Wildcards can be used to specify multiple files.
If a UserName or WGname includes spaces then it must be surrounded
with quotes e.g. “Authenticated Users”
If no options are specified CACLS will display the ACLs for the file(s)
Setting Deny permission (/D) will deny access to a user even if they also
belong to a group that grants access.
Limitations
Cacls cannot display or modify the ACL state of files locked in exclusive
use.
Cacls cannot set the following permissions: change permissions, take
ownership, execute, delete use XCACLS to set any of these.
Using CACLS
The CACLS command does not provide a /Y switch to automatically
answer ‘Y’ to the Y/N prompt. However, you can pipe the ‘Y’ character into
the CACLS command using ECHO, use the following syntax:
ECHO Y| CACLS filename /g username:permission
To edit a file you must have the “Change” ACL (or be the file’s owner)
To use the CACLS command and change an ACL requires “FULL Control”
File “Ownership” will always override all ACL’s - you always have Full
Control over files that you create.
If CACLS is used without the /E switch all existing rights on [pathname]
will be replaced, any attempt to use the /E switch to change a
[user:permission] that already exists will raise an error. To be sure the CALCS
command will work without errors use /E /R to remove ACL rights for the
user concerned, then use /E to add the desired rights.
The /T option will only traverse subfolders below the current directory
If no options are specified CACLS will display the current ACLs
e.g. To display the current folder
CACLS .
Display permissions for one file
CACLS MyFile.txt
Display permissions for multiple files
CACLS *.txt
Inherited folder permissions are displayed as:
OI - Object inherit - This folder and files. (no inheritance to
subfolders)
CI - Container inherit - This folder and subfolders.
IO - Inherit only - The ACE does not apply to the current
file/directory
These can be combined as folllows:
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
(OI) (IO) Files only.
So BUILTIN\Administrators:(OI)(CI)F means that both files and
Subdirectories will inherit ‘F’ (Fullcontrol)
similarly (CI)R means Directories will inherit ‘R’ (Read folders only =
List permission)
To actually change the inheritance of a folder/directory use iCACLS
/grant or iCACLs /deny
When cacls is applied to the current folder only there is no inheritance
and so no output.
Errors when changing permissions
If a user or group has a permission on a file or folder and you grant a
second permission to the same user/group on the same folder, NTFS will
sometimes produce the error message “The parameter is incorrect” To fix this
(or prevent it happening) revoke the permission first (/e /r) and then reapply
(/e /g)
Examples:
Add Read-Only permission to a single file
CACLS myfile.txt /E /G “Power Users”:R
Add Full Control permission to a second group of users
CACLS myfile.txt /E /G “FinanceUsers”:F
Now revoke the Read permissions from the first group
CACLS myfile.txt /E /R “Power Users”
Now give the first group Full-control:
CACLS myfile.txt /E /G “Power Users”:F
Give the Finance group Full Control of a folder and all sub folders
CACLS c:\docs\work /E /T /C /G “FinanceUsers”:F
DATE
Display or change the date
Syntax
to display the date
DATE /T
to set the system date
DATE
or
DATE <date_today>
United States 001 01/23/1997 5:35:00.00p
Czechoslovakia 042 23.01.1997 17:35:00
France 033 23.01.1997 17:35:00
Germany 049 23.01.1997 17:35:00
Latin America 003 23/01/1997 5:35:00.00p
International English 061 23/01/1997 17:35:00.00
Portugal 351 23-01-1997 17:35:00
Finland 358 23.1.1997 17.35.00
Switzerland 041 23.01.97 17 35.00
Norway 047 23.01.97 17:35:00
Belgium 032 23/01/97 17:35:00
Brazil 055 23/01/97 17:35:00
Italy 039 23/01/97 17.35.00
United Kingdom 044 23/01/97 17:35:00.00
Denmark 045 23-01-97 17.35.00
Netherlands 031 23-01-97 17:35:00
Spain 034 3/12/98 17:35:00
Hungary 036 1997.01.23 17:35:00
Canadian-French 002 1997-01-23 17:35:00
Poland 048 1997-01-23 17:35:00
Sweden 046 1997-01-23 17.35.00
Date Formatting
In Control Panel Regional settings a short date STYLE can be set. This can be
used to change the date separator, the order (e.g. dd/mm/yyyy or
mm/dd/yyyy) and the number of characters used to display days and months.
DEFRAG
Defragment hard drive.
Syntax
DEFRAG <volume> [-a] [-f] [-v] [-?]
Options
volume drive letter or mount point (d: or d:\vol\mountpoint)
-a Analyze only
-f Force defragmentation even if free space is low
-v Verbose output
Example:
DEFRAG c: -f
DEL
Delete one or more files.
Syntax
DEL [options] [/A:file_attributes] files_to_delete
Key
files_to_delete : This may be a filename, a list of files or a Wildcard
options
/P Give a Yes/No Prompt before deleting.
/F Ignore read-only setting and delete anyway (FORCE)
/S Delete from all Subfolders (DELTREE)
/Q Quiet mode, do not give a Yes/No Prompt before deleting.
/A Select files to delete based on file_attributes
file_attributes:
R Read-only -R NOT Read-only
S System -S NOT System
H Hidden -H NOT Hidden
A Archive -A NOT Archive
Wildcards: These can be combined with part of a filename
* Match any characters
? Match any ONE character
Examples:
To delete HelloWorld.TXT
DEL HelloWorld.TXT
Folders
If a folder name is given instead of a file, all files in the folder will be deleted,
but the folder itself will not be removed.
Temporary Files
You should clear out TEMP files on a regular basis - this is best done at
startup when no applications are running. To delete all files in all subfolders
of C:\temp\ but leave the folder structure intact:
DEL /F /S /Q %TEMP%
Deleting a file will not prevent third party utilities from un-deleting it again,
however you can turn any file into a zero-byte file to destroy the file
allocation chain like this:
Previous versions of Windows had the DELTREE command that deletes all
files and sub folders.
DEL /s will delete all files
RD /s will remove all files and folders including the root folder.
:: Remove all files and subfolders but NOT the root folder
:: From tip 617 at JsiFAQ.com
@echo off
pushd %1
del /q *.*
for /f “Tokens=*” %%G in (‘dir /B’) do rd /s /q “%%G”
popd
DELPROF (*)
Delete windows user profiles.
Syntax
DELPROF [options days]
Key
/Q Quiet, no confirmation.
/I Ignore errors and continue deleting.
/P Prompts for confirmation before deleting each profile.
/C:\computer_name
Delete profiles on a remote computer.
/D:Number_of_days
Only delete profiles that have been inactive for
‘X’ Number of days (or greater)
/R Delete roaming profile cache only ##
## = New in version 5.2 (XP resource kit)
Example:
delprof /D:14
DEVCON.exe (Download)
Device Manager
Syntax
devcon.exe [-r] [-m:\machine] command [arg…]
devcon.exe help command
Key
-r Reboot the machine after command is complete, if needed.
machine Name of target machine.
command The command to perform (see below).
arg… One or more arguments if required by command.
Commands:
classfilter Allow modification of class filters.
classes List all device setup classes.
disable Disable devices that match the specific hardware/instance ID.
driverfiles List driver files installed for devices.
drivernodes List all the driver nodes of devices.
enable Enable devices that match the specific hardware/instance ID.
find Find devices that match the specific hardware/instance ID.
findall Find devices including those that are not present.
help Display this information.
hwids List hardware ID’s of devices.
install Manually install a device.
listclass List all devices for a setup class.
reboot Reboot local machine.
remove Remove devices that match the specific hardware/instance ID.
rescan Scan for new hardware.
resources List hardware resources of devices.
restart Restart devices that match the specific hardware/instance ID.
stack List expected driver stack of devices.
status List running status of devices.
update Manually update a device.
UpdateNI Manually update a device without user prompt
SetHwID Add, delete, and change the order of hardware IDs of root-enumerated devices.
Examples:
List all known PCI devices on the computer pc64.
devcon -m:\pc64 find pci\*
Install a new instance of the Microsoft loopback adaptor and restart if
required. This creates a new root-enumerated device node with which you can
install a “virtual device,” such as the loopback adaptor.
devcon -r install %WINDIR%\Inf\Netloop.inf *MSLOOP
List all known setup classes. Displays both the short name and the
descriptive name.
devcon classes
Lists files that are associated with each device in the ports setup class.
devcon driverfiles =ports
Disable all devices that have a hardware ID that ends in “MSLOOP”
(including “*MSLOOP”).
devcon disable *MSLOOP
List all compatible drivers for the device ROOT\PCI_HAL\PNP0A03.
This can be used to determine why an integral device information (.inf) file
was chosen, instead of a third-party .inf file.
devcon drivernodes @ROOT\PCI_HAL\PNP0A03
Enable all devices that have a hardware ID of “*MSLOOP”. The single
quotation mark indicates that the hardware ID must be taken literally (in other
words, the asterisk [“*”] actually is an asterisk; it is not a wildcard character).
devcon enable ‘*MSLOOP
List device instances of all devices that are present on the local
computer.
devcon find *
List all known peripheral component interconnect (PCI) devices that are
on the local computer (this command assumes that a device is PCI if it has a
hardware ID that is prefixed by “PCI\”).
devcon find pci\*
List devices that are a member of the ports setup class and that contain
“PNP” in their hardware ID.
devcon find =ports *pnp*
List devices that are present that are a member of the ports setup class
and that are in the “root” branch of the enum tree (the instance ID is prefixed
by “root\”). Note that you should not make any programmatic assumption
about how an instance ID is formatted. To determine root devices, you can
look at device status bits. This feature is included in DevCon to aid in
debugging.
devcon find =ports @root\*
List “nonpresent” devices and devices that are present for the ports class.
This includes devices that have been removed, devices that have been moved
from one slot to another and, in some cases, devices that have been
enumerated differently due to a BIOS change.
devcon findall =ports
List all devices that are present for each class named (in this case, USB
and 1394).
devcon listclass usb 1394
Remove all USB devices. Devices that are removed are listed with their
removal status.
devcon remove @usb\*
Rescan for new Plug and Play devices.
devcon rescan
List the resources that are used by all devices in the ports setup class.
devcon resources =ports
Restart the loopback adaptor ROOT\*MSLOOP\0000. The single
quotation mark in the command indicates that the instance ID must be taken
literally.
devcon restart =net @‘ROOT\*MSLOOP\0000
List all hardware IDs of mouse class devices on the system.
devcon hwids=mouse
Assign the hardware ID, beep, to the legacy beep device.
devcon sethwid @ROOT\LEGACY_BEEP\0000 := beep
List the status of each device present that has an instance ID that begins
with “pci\”.
devcon status @pci\*
List the status of an Advanced Configuration and Power Interface
(ACPI)-enumerated serial port.
devcon status @ACPI\PNP0501\1
List the status of all COM ports.
devcon status *PNP05*
Errorlevels returned by DevCon.exe:
0 = success.
1 - restart is required.
2 = failure.
3 = syntax error.
DIR
Display a list of files and subfolders
Syntax
DIR [pathname(s)] [display_format] [file_attributes] [sorted] [time] [options]
Key
[pathname] The drive, folder, and/or files to display,
this can include wildcards:
* Match any characters
? Match any ONE character
[display_format]
/P Pause after each screen of data.
/W Wide List format, sorted horizontally.
/D Wide List format, sorted by vertical column.
[file_attributes] /A:
/A:D Folder /A:-D NOT Folder
/A:R Read-only /A:-R NOT Read-only
/A:H Hidden /A:-H NOT Hidden
/A:A Archive /A:-A NOT Archive
/A Show all files
several attributes may be combined e.g. /A:HD-R
[sorted] Sorted by /O:
/O:N Name /O:-N Name
/O:S file Size /O:-S file Size
/O:E file Extension /O:-E file Extension
/O:D Date & time /O:-D Date & time
/O:G Group folders first /O:-G Group folders last
several attributes may be combined e.g. /O:GEN
[time] /T: the time field to display & use for sorting
/T:C Creation
/T:A Last Access
/T:W Last Written (default)
[options]
/S include all subfolders.
/R Display alternate data streams. (Vista and above)
/B Bare format (no heading, file sizes or summary).
/L use Lowercase.
/Q Display the owner of the file.
/N long list format where filenames are on the far right.
/X As for /N but with the short filenames included.
/C Include thousand separator in file sizes.
/-C don’t include thousand separator in file sizes.
/4 Display four-digit years
To obtain a bare DIR format (no heading or footer info) but retain all the
details, pipe the output of DIR into FIND, this assumes that your date
separator is /
DIR c:\temp\*.* | FIND “/”
FOR /f “tokens=*” %%G IN (‘dir c:\temp\*.* ^| find “/”’) DO echo %%G
Normally DIR /b will return just the filename, however when displaying
subfolders with DIR /b /s the command will return a full pathname.
/Q:# Quota limit, mark folders that exceed the size (#) with a “!”.
set %errorlevel% to ONE if any folders are found that
exceed the specified size
Note: the ‘-‘ symbol can be used in place of the ‘/’ symbol.
Example
DISKCOMP.com
Compare the content of two floppy disks.
Syntax
DISKCOMP floppy_drive1: floppy_drive2:
Key
floppy_drive is the drive letter
For Example:
DISKCOMP A: A:
DISKCOPY.com
Copy the content of one floppy disk to another.
Syntax
DISKCOPY flopppy_drive1: floppy_drive2: [/V]
Key
/V Verify that the information was copied correctly.
DiskPart (Windows 7)
Disk Administration, Partition a disk. This page documents the Windows
7/2008 version of Diskpart, an earlier version of Diskpart is supplied in the
2003 Resource kit with a reduced set of options.
Syntax
DISKPART
Commands you may then issue at the DISKPART prompt:
LIST Disk
LIST Partition
LIST Volume
SELECT Disk=n
SELECT Partition=n
SELECT Volume=n_or_d (Number or Drive Letter)
DETAIL Disk
DETAIL Partition
DETAIL volume
ACTIVE (set the current in-focus partition to be the system partition)
ASSIGN (allocate the next free drive letter)
ASSIGN LETTER=E (Choose a free letter)
ATTRIBUTES DISK [{set | clear}] [readonly] [noerr]
ATTRIBUTES VOLUME [{set | clear}] [{hidden | readonly | nodefaultdriveletter |
shadowcopy}] [noerr]
AUTOMOUNT [enable] [disable] [scrub] [noerr]
FILESYSTEMS (Use ‘Select Volume’ first)
HELP
INACTIVE (mark a system/boot partition as inactive [don’t boot], use ‘Select Partition’ first)
OFFLINE disk [noerr] (Take the current disc offline, use ‘Select Disk’ first)
ONLINE {disk|volume} [noerr]
REM (remark/comment)
REMOVE letter=E [dismount] [noerr] (Remove drive letter E from the in-focus partition)
REMOVE mount=path [dismount] [noerr] (Remove mount point from the in-focus partition)
REMOVE /ALL [dismount] [noerr] (Remove ALL current drive letters and mount points)
RESCAN (Locate new disks that have been added to the computer)
SHRINK [desired=n] [minimum=n] [nowait] [noerr] (Reduce the size of the in-focus volume)
SHRINK querymax [noerr]
EXIT
UNIQUEID disk [id={dword | GUID}] [noerr] (Display or set the GUID partition table
identifier
or MBR signature for the disk with focus)
Commands to Manage Basic Disks:
ASSIGN MOUNT=path (Choose a mount point path for the volume)
CREATE PARTITION Primary Size=50000 (50 GB)
CREATE PARTITION Extended Size=25000
CREATE PARTITION logical Size=25000
DELETE Partition
EXTEND Size=10000
GPT attributes=n (assign GUID Partition Table attributes)
SET id=byte|GUID [override] [noerr] (Change the partition type)
Commands to Manage Dynamic Disks:
ADD disk=n (Add a mirror to the in-focus SIMPLE volume on the specified disk
see ‘Diskpart Help’ for more.)
BREAK disk=n (Break the current in-focus mirror)
CREATE VOLUME Simple Size=n Disk=n
CREATE VOLUME Stripe Size=n Disk=n,n,…
CREATE VOLUME Raid Size=n Disk=n,n,…
DELETE DISK
DELETE PARTITION
DELETE VOLUME
EXTEND Disk=n [Size=n]
EXTEND Filesystem [noerr]
IMPORT [noerr] (Import a foreign disk group, use ‘Select Disc’ first)
RECOVER [noerr] (Refresh disc pack state, attempt recovery on an invalid pack,
& resynchronize stale plex/parity data.)
REPAIR disk=n [align=n] [noerr] (Repair the RAID-5 volume with focus, replace with the
specified dynamic disk)
RETAIN (Prepare an existing dynamic simple volume to be used as a boot or system volume)
Commands to Convert Disks
CONVERT basic
CONVERT dynamic
CONVERT gpt
CONVERT mbr
CLEAN [ALL] (remove all partition and volume info from the hard drive)
FORMAT [{fs=ntfs|fat|fat32] [revision=x.xx] | recommended}]
[label=”label“] [unit=n] [quick] [compress]
[override] [nowait] [noerr]
The diskpart commands may be placed in a text file (one command per
line) and used as an input file to diskpart.exe:
DiskPart.exe < myscript.txt
Example:
SELECT DISK=0
CREATE PARTITION PRIMARY
ASSIGN LETTER=E
SELECT PARTITION=1
FORMAT FS=NTFS LABEL=“New Volume” QUICK
EXIT
noerr - This option is for scripting only. With noerr set, when an error is
encountered, DiskPart will continue to process commands as if the error did
not occur. Without this parameter, an error causes DiskPart to exit with an
error code.
When selecting a volume or partition, you may use either the number or
drive letter or the mount point path.
Always back up the hard disk before running diskpart.
DOSKEY.exe
Recall and edit commands at the DOS prompt, and create macros. You
cannot run a Doskey macro from a batch file.
Syntax
DOSKEY [options] [macroname=[text]]
Key
macroname : A short name for the macro.
text : The commands you want to recall.
options : for working with macros…
/MACROFILE=filename Specify a file of macros to install
/MACROS Display all Doskey macros
/EXENAME=exename Specify an executable other than cmd.exe
/MACROS:exename Display all Doskey macros for the given executable
/MACROS:ALL Display all Doskey macros for all executables
ALT+F10 Clear macro definitions
options : for working with the Command Buffer…
/HISTORY : Display all commands stored in memory.
/LISTSIZE=size : Limit the number of commands remembered by the buffer.
/REINSTALL : Install a new copy of Doskey (clears the buffer).
In normal use the command line is always in overwrite mode, DOSKEY can be used to
change this to Insert, the insert key will always toggle from one to the other
/INSERT : By default new text you type at the command line
will be inserted in old text
/OVERSTRIKE : By default new text you type at the command line
will overwrite old
In addition to the above, DOSKEY is loaded into memory for every cmd
session so you can use Keyboard shortcuts at the command line
The size of the command history can be set from Control Panel, Console or
from the properties of any cmd shortcut. Clear all history with DOSKEY
/REINSTALL
Examples:
A macro to open notepad
DOSKEY note=notepad.exe
DSACLS.exe
View or Edit ACLs (access control entries) for objects in Active
Directory.
Syntax
DSACLS “[\Computer\]ObjectDN” [/A] [/D PermissionStatement [PermissionStatement]…]
[/G PermissionStatement [PermissionStatement]…] [/I:{T | S | P}]
[/N] [/P:{Y | N}]
[/R {User | Group} [{User | Group}]…] [/S [/T]]
PermissionStatements:
{User | Group}:Permissions[;{ObjectType | Property}][;InheritedObjectType]
Key
ObjectDN Distinguished name of the object.
If omitted will be taken from standard input (stdin)
/A Add ownership and auditing information to the results.
/D Deny permissions to a user or group
/G Grant permissions to a user or group.
/I: Inheritance
T The object and its child objects (default)
S The child objects only
P The object and child objects down one level only
/N Replace the current ACEs in the ACL.
By default, dsacls adds the ACE to the ACL.
ECHO
Display messages on screen, turn command-echoing on or off.
Syntax
ECHO [ON | OFF]
ECHO [message]
Key
ON : Display each line of the batch on screen (default)
OFF : Only display the command output on screen
message : a string of characters to display
Type ECHO without parameters to display the current echo setting (ON
or OFF).
In most batch files you will want ECHO OFF, turning it ON can be useful
when debugging a problematic batch script.
In a batch file, the @ symbol is the same as ECHO OFF applied to the current
line only.
Normally a command is executed and takes effect from the next line onwards,
@ is a rare example of a command that takes effect immediately.
Command characters will normally take precedence over the ECHO statement
e.g. The redirection and pipe characters: & < > | ON OFF
To override this behaviour you can escape each command character with ^ as
follows:
ECHO Nice ^&Easy
ECHO Salary is ^> Commision
ECHO Name ^| Username ^| Expiry Date
ECHO:Off On Holiday
ECHO %_department%
Echo a file
Echo a sound
The following command in a batch file will trigger the default beep on most
PC’s
ECHO
Use Ctrl-G (or ‘Alt’ key, and 7 on the numeric keypad) to get this character
(ascii 7)
ECHO.
Streams allow one file to contain several separate forks of information (like
the macintosh resource fork)
Creating streams:
Echo This is stream1 > myfile.dat:stream1
Echo This is stream2 > myfile.dat:stream2
Displaying streams:
More < myfile.dat:stream1
More < myfile.dat:stream2
FOR /f “delims=*” %%G in (myfile.dat:stream1) DO echo %%G
FOR /f “delims=*” %%G in (myfile.dat:stream2) DO echo %%G
A data stream file can be successfully copied and renamed despite the
fact that most applications and commands will report a zero length file. The
file size can be calculated from remaining free space. The file must always
reside on an NTFS volume.
ENDLOCAL
End localisation of environment changes in a batch file. Pass variables
from one batch file to another.
Syntax
ENDLOCAL
By putting ENDLOCAL & SET commands on a single line you are able to
SET a variable just before the localisation is ended by the ENDLOCAL
command.
Examples:
::Sales.cmd
@Echo off
SETLOCAL
Set _item=“Ice Cream Maker”
Set _price=450
ENDLOCAL & SET _return1=%_item%& SET _return2=%_price%
::Results.cmd
@Echo off
SETLOCAL
CALL Sales.cmd
Echo [%_return1%] will cost [%_return2%]
::SubDemo.cmd
@Echo off
SETLOCAL
CALL sub_products
Echo [%_return1%] will cost [%_return2%]
:sub_products
SETLOCAL
Set _item=“Coffee Grinder”
Set _price=150
ENDLOCAL & SET _return1=%_item%& SET _return2=%_price%
Examples:
EXIT
Quit the current batch script, quit the current subroutine or quit the
command processor (CMD.EXE) optionally setting an errorlevel code.
Syntax
EXIT [/B] [exitCode]
Key
/B When used in a batch script, this option will exit
only the script (or subroutine) but not CMD.EXE
exitCode Sets the %ERRORLEVEL% to a numeric number.
If quitting CMD.EXE, set the process exit code no.
You should never attempt to directly write to the %errorlevel% variable,
(i.e. don’t try anything like SET errorlevel…) using the EXIT command
provides a safe way to alter the value of the built-in errorlevel variable.
Examples
:: Exit if a required file is missing
@echo off
If not exist MyimportantFile.txt Exit /b
Echo If we get this far the file was found
:: Set the error level to 5
@echo off
call :setError
echo %errorlevel%
goto :eof
:setError
exit /B 5
To make this more flexible you can change the subroutine to set any
errorlevel like this:
:setError
exit /B %1
Now you can call the subroutine: call :setError 6 replacing 6 with
whatever value you need the errorlevel to be set to.
EXPAND
Uncompress one or more compressed files.
Syntax
EXPAND Source Destination
EXPAND -r Source Destination
EXPAND -r Source
Options
Source : Source filename or a wildcard
Destination : Destination filename or folder
-r : Rename the files
EXPAND
Uncompress one or more compressed files.
Syntax
EXTRACT [options] CAB_file [filenames]
Key
CAB_file : Cabinet file
filenames : Name of the file to extract from the cabinet
Wild cards (*.*) (.) and multiple files are valid
options
/A Process ALL cabinets. (where CABs are linked)
/C If the CAB contains one file then /C will
copy from DMF disks
/D Display CAB directory
/E Extract all (use instead of *.* to extract all files)
/L dir Location to place extracted files (default is current folder)
/Y Overwrite files without any prompt
FC.exe
Compare the contents of two files or sets of files. Display any lines
which do NOT match.
Syntax
FC /B pathname1 pathname2
FC [options] pathname1 pathname2
Key
/B : Perform a binary comparison.
options
/C : Do a case insensitive string comparison
/A : Displays only first and last lines for each set of differences.
/U : Compare files as UNICODE text files.
/L : Compares files as ASCII text. (default)
/N : Display line numbers (ASCII only)
/LBn: Limit the number of lines that will be read, “n” sets a maximum number
of mismatches after which the File Comparison will abort (resync failed)
When FC aborts (resync failed) then “n” number of mismatches will be shown.
/nnnn : Specify a number of consecutive lines that must match after a mismatch.
This can be used to prevent the display of the two files from getting
too out of sync
/T : Do not expand tabs to spaces.
/W : Compress white space (tabs and spaces) for comparison.
Example:
If two files are compared and the four lines of text match as follows
1: different
2: same
3: same
4: different
Specifying /nnnn =2 the file compare will display the 4th line and continue
Specifying /nnnn =3 the file compare will halt at the 4th line (files too
different)
Specifying /LB1 the file compare will halt after the first line
FIND
Search for a text string in a file & display all the lines where it is found.
Syntax
FIND [/V] [/C] [/N] [/I] “string” [pathname(s)]
key
/V : Display all lines NOT containing the specified string.
/C : Count the number of lines containing the string.
/N : Display Line numbers.
/I : Ignore the case of characters when searching for the string.
“string“ : The text string to find (must be in quotes).
[pathname] : A drive, file or files to search.
If a [pathname] is not specified, FIND will prompt for text input or will
accept text piped from another command.
(use CTRL-Z to end manual text input)
Examples:
–––- NAMES.TXT
Arnold Jones, 127 Scotland Street, Edinburgh
FINDSTR
Search for strings in files.
Syntax
FINDSTR [options] [/F:file] [/C:string] [/G:file]
[/D:DirList] [/A:color_attr] [/OFF[LINE]] [string(s)] [pathname(s)]
Key
string Text to search for.
pathname(s) The file(s) to search.
/C:string Use string as a literal search string.
/G:file Get search string from a file (/ stands for console).
/F:file Get a list of pathname(s) from a file (/ stands for console).
/A:color_attr Display filenames in colour (2 hex digits)
/d:dirlist Search a comma-delimited list of directories.
options may be any combination of the following switches:
/I Case-insensitive search.
/S Search subfolders.
/P Skip any file that contains non-printable characters
/OFF[LINE] Do not skip files with the OffLine attribute set.
/L Use search string(s) literally.
/R Use search string(s) as regular expressions.(default)
/B Match pattern if at the Beginning of a line.
/E Match pattern if at the END of a line.
/X Print lines that match exactly.
/V Print only lines that do NOT contain a match.
/N Print the line number before each line that matches.
/M Print only the filename if a file contains a match.
/O Print character offset before each matching line.
When the search string contains multiple words (separated with spaces)
then FINDSTR will show show lines that contains any one word - (an OR of
each word) - this behaviour is reversed if the string argument is prefixed with
/C.
Regular Expressions
(Searching for patterns of text)
The FINDSTR syntax notation can use the following metacharacters which
have special meaning either as an operator or delimiter.
. Wildcard: any character
* Repeat: zero or more occurances of previous character or class
^ Line position: beginning of line
$ Line position: end of line
[class] Character class: any one character in set
[^class] Inverse class: any one character not in set
[x-y] Range: any characters within the specified range
\x Escape: literal use of metacharacter x
\<xyz Word position: beginning of
xyz\> Word position: end of word
Metacharacters are most powerful when they are used together. For
example, the combination of the wildcard character (.) and repeat (*)
character is similar in effect to the filename wildcard (*.*)
.* Match any string of characters
Examples:
Search every file in the current folder and all subfolders for the word “Smith”,
regardless of upper/lower case, note that /S will only search below the current
directory:
Search all the text files in the current folder for the string “fiona”, display the
filenames in White on Green.
FINDSTR /A:2F /C:fiona *.txt
To find every line containing the word SMITH, preceeded by any number of
spaces, and to prefix each line found with a consecutive number:
Find any words that begin with the letters ‘comp’, such as ‘computerise’ or
‘compete’
When preparing a source or script file, place each item on a new line.
For example: to use the search criteria in Crit.txt to search the files listed in
Files.txt and then store the results in the file RESULTS.txt:
FOR /F
Loop command: against a set of files - conditionally perform a command
against each item.
Syntax
FOR /F [“options”] %%parameter IN (filenameset) DO command
FOR /F [“options“] %%parameter IN (“Text string to process”) DO command
Key
options:
delims=xxx The delimiter character(s) (default = a space)
skip=n A number of lines to skip at the beginning of the file.
(default = 0)
eol=; Character at the start of each line to indicate a comment
The default is a semicolon ;
tokens=n Specifies which numbered items to read from each line
(default = 1)
usebackq Specify `back quotes`:
- Use double quotes to quote long file names in filenameset.
- Use single quotes for ‘Text string to process’
(useful if the text string contains double quotes)
Filenameset A set of one or more files. Wildcards may be used.
If (filenameset) is a period character (.) then FOR will
loop through every file in the folder.
command The command to carry out, including any
command-line parameters.
%%parameter A replaceable parameter:
in a batch file use %%G (on the command line %G)
FOR /F processing of a text file consists of reading the file, one line of
text at a time and then breaking the line up into individual items of data called
‘tokens’. The DO command is then executed with the parameter(s) set to the
token(s) found.
By default, /F breaks up the line at each blank space ” “, and any blank lines
are skipped, this default parsing behavior can be changed by applying one or
more of the “options” parameters. The option(s) must be contained within “a
pair of quotes”
Within a FOR loop the visibility of FOR variables is controlled via
SETLOCAL EnableDelayedExpansion
Tokens
tokens=2,4,6 will cause the second, fourth and sixth items on each line to be
processed
tokens=2-6 will cause the second, third, fourth, fifth and sixth items on each
line to be processed
tokens=3* will cause the 3rd and all subsequent items on each line to be
processed
Delims
More than one delimiter may be specified so a string like
‘abcd+efg+hijk+lmno;pqr;stu+vwzyz’ can be broken up using “delims=;+”.
You can use any character as a delimiter, but they are case sensitive.
If you don’t specify delims it will default to “delims=<tab><space>”
n.b. some text editors will enter the TAB character as a series of spaces,
specifying more than one delimiter has been known to cause problems with
some data sets.
usebackq
This option is useful when dealing with a filenameset that is a long filename
containing spaces, it allows you to put double quotes around the filename.
The backquote character ` is just below the ESC key on most keyboards.
eol
The default end-of-line character is a semicolon ‘;’ when the FOR command
reads a text file (or even a character string), any line that STARTS with the
eol character will be ignored. In other words it is treated as a comment.
Use eol=X to change the eol character to X.
Most often you will want to turn this feature off so that every line of your data
file is processed, in theory “eol=” should turn this feature off, but in practice
this fails to work correctly so instead set eol to some unusual character that
you don’t expect to ever be in the data file e.g. “eol=€” or “eol=¬”.
Examples
Extracting data from this text file:
January,Snowy,02
February,Rainy,15
March,Sunny,25
The tricky part is splitting up each the line into the right tokens, in this case
I’m splitting on the comma character ‘,’ this splits the line into 3 chunks of
text and we pull out the first and third items with “tokens=1,3”
January 02
February 15
March 25
FOR parameter names are global, so in complex scripts which call one FOR
statement from within another FOR statement you can refer to both sets of
parameters. You cannot have more than 26 parameters active at any one time.
FOR /F
Loop command: against the results of another command.
Syntax
FOR /F [“options”] %%parameter IN (‘command_to_process’) DO command
Key
options:
delims=xxx The delimiter character(s)
(default = a space)
skip=n A number of lines to skip at the beginning.
(default = 0)
eol=; Character at the start of each line to indicate a comment
The default is a semicolon ;
tokens=n Specifies which numbered items to
read from each line
(default = 1)
usebackq Specify `back quotes`
the command_to_process is placed in `BACK quotes`
instead of ‘straight’ quotes
command_to_process : The output of the ‘command_to_process’ is
passed into the FOR parameter.
command : The command to carry out, including any
command-line parameters.
%%parameter : A replaceable parameter:
in a batch file use %%G (on the command line %G)
The FOR command is the answer to innumerable questions where you want
to take the output of some command, store it in a variable (%%G) then do
something with the result.
For example the PING command returns serveral lines including one
like:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
To select that one line of output, you can search for the text “loss”
(which is always present), then use the Tokens parameter to select the number
of lost packets, here this is 0 but it will vary each time you run the command.
set _ping_cmd=ping -n 5 127.0.0.1
FOR /f “tokens=4 delims=(=” %%G IN (‘%_ping_cmd% ^|find “loss”’)
DO echo Result is [%%G]
The tricky part is always splitting up the line of interest into the right
tokens, in this case I’m splitting on the characters ‘=’ and ‘(‘
these two characters split the line into 5 chunks of text and we pull out the
fourth one with “tokens=4”
By default, /F breaks up the command output at each blank space, and
any blank lines are skipped.
You can override this default parsing behavior by specifying the “options”
parameter. The options must be contained within “quotes”
usebackq
This option is useful when dealing with a command that already contains
one or more straight quotes.
The backquote character ` is just below the ESC key on most keyboards. See
the FOR /F page for other effects of usebackq.
Tokens
tokens=2,4,6 will cause the second, fourth and sixth items on each line to be
processed
tokens=2-6 will cause the second, third, fourth, fifth and sixth items on each
line to be processed
tokens=3* will cause the 3rd and all subsequent items on each line to be
processed
Delims
More than one delimiter may be specified so a string like
‘abcd+efg+hijk;lmno;pqr’ can be broken up using “delims=;+”.
You can use any character as a delimiter, but they are case sensitive.
If you don’t specify delims it will default to “delims=<tab><space>”
n.b some text editors will enter the TAB character as a series of spaces,
specifying more than one delimiter has been known to cause problems with
some data sets.
eol
The default end-of-line character is a semicolon ‘;’ when the FOR command
reads a text file (or even a character string), any line that STARTS with the
eol character will be ignored. In other words it is treated as a comment.
Use eol=X to change the eol character to X.
Most often you will want to turn this feature off so that every line of your data
file is processed, in theory “eol=” should turn this feature off, but in practice
this fails to work correctly so instead set eol to some unusual character that
you don’t expect to ever be in the data file e.g. “eol=€” or “eol=¬”.
Examples:
To ECHO from the command line, the name of every environment variable.
FOR /F “delims==” %G IN (‘SET’) DO @Echo %G
Although the above is a trivial example, being able to set %%G equal to each
long filename in turn could allow much more complex processing to be done.
FOR
Conditionally perform a command several times.
syntax-FOR-Files
FOR %%parameter IN (set) DO command
syntax-FOR-Files-Rooted at Path
FOR /R [[drive:]path] %%parameter IN (set) DO command
syntax-FOR-Folders
FOR /D %%parameter IN (folder_set) DO command
syntax-FOR-List of numbers
FOR /L %%parameter IN (start,step,end) DO command
syntax-FOR-File contents
FOR /F [“options”] %%parameter IN (filenameset) DO command
FOR /F [“options”] %%parameter IN (“Text string to process”) DO command
syntax-FOR-Command Results
FOR /F [“options”] %%parameter IN (‘command to process’) DO command
The first parameter has to be defined using a single character, I tend to use the
letter G.
In each iteration of a FOR loop, the IN ( ….) clause is evaluated and %%G
set to a different value
If this results in a single value then %%G is set equal to that value and the
command is performed.
If this results in a multiple values then extra parameters are implicitly defined
to hold each. These are automatically assigned in alphabetical order %%H
%%I %%J …(implicit parameter definition)
Also if the parameter refers to a file, you can use an enhanced variable
reference to quickly extract the filename/path/date/size.
Example
FOR /F “tokens=1-5” %%G IN (“This is a long sentence”) DO @echo
%%G %%H %%J
will result in the output
This is long
You can of course pick any letter of the alphabet other than %%G.
%%G is a good choice because it does not conflict with any of the pathname
format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-
conflicting letters for use as implicit parameters.
G > H > I > J > K > L > M
Running multiple commands in a FOR loop
Within a FOR loop, variables are expanded at the start of the loop and don’t
update until the entire DO section has completed.
The following example counts the files in the current folder, but %count%
always returns 1:
@echo off
SET count=1
FOR /f “tokens=*” %%G IN (‘dir /b’) DO (
echo %count%:%%G
set /a count+=1 )
To update variables within each iteration of the loop we must either use
EnableDelayedExpansion or else use the CALL :subroutine mechanism as
shown below:
@echo off
SET count=1
FOR /f “tokens=*” %%G IN (‘dir /b’) DO (call :subroutine”%%G”)
GOTO :eof
:subroutine
echo %count%:%1
set /a count+=1
GOTO :eof
Nested FOR commands
If Command Extensions are disabled, the FOR command will only support
the basic syntax with no enhanced variables:
FOR %%parameter IN (set) DO command [command-parameters]
FORFILES.exe (*)
Select a file (or set of files) and execute a command on each file. Batch
processing.
Syntax
FORFILES [/p Path] [/m Mask] [/s] [/c Command] [/d [+ | -] {dd/MM/yyyy | dd}]
Key
/p Path The Path to search (default=current folder)
/s Recurse into sub-folders
/C command The command to execute for each file.
Wrap the command string in double quotes.
Default = “cmd /c echo @file”
The Command variables listed below can also be used in the
command string.
/D date Select files with a last modified date greater than or
equal to (+), or less than or equal to (-),
the specified date using the “dd/MM/yyyy” format;
/D + dd Select files with a last modified date greater than or
equal to the current date plus “dd” days. (in the future)
/D - dd Select files with a last modified date less than or
equal to the current date minus “dd” days. (in the past)
A valid “dd” number of days can be any number in
the range of 0 to 32768. (89 years)
“+” is taken as default sign if not specified.
Command Variables:
@file The name of the file.
@fname The file name without extension.
@ext Only the extension of the file.
@path Full path of the file.
@relpath Relative path of the file.
@isdir Returns “TRUE” if a file type is a directory,
and “FALSE” for files.
@fsize Size of the file in bytes.
@fdate Last modified date of the file.
@ftime Last modified time of the file.
To include special characters in the command line, use the hex code for
the character in 0xHH format (ex. 0x09 is theTAB character, 0x22 is the
double quote ” character.) so “C:\Program Files\” becomes ^0x22C:\Program^
Files\^0x22
Internal CMD.exe commands must be preceded with “cmd /c”.
If ForFiles finds one or more matches if will return %errorlevel% =0
If ForFiles finds no matches if will return %errorlevel% =1 and will print
“ERROR: No files found with the specified search criteria.”
The old NT4 version of ForFiles used unix style -parameters, and could
only match dates newer than a specified date using the following command
variables names: (which must be upper case) @FILE,
@FNAME_WITHOUT_EXT, @EXT, @PATH, @RELPATH, @ISDIR,
@FSIZE, @FDATE, @FTIME
The Windows 2000 version of ForFiles also used unix-style parameters but is
otherwise the same as current versions.
Last modified dates set in the future are not common but can happen
when your computer clock date/time is changed e.g. due to daylight savings
time.
Examples:
Delete the testfile if it is is 5 days old or older:
C:\> forfiles /m testfile.txt /c “cmd /c Del testfile.txt ” /d -5
Find .xls file that were last modified 30 days ago or older
C:\> FORFILES /M *.xls /C “cmd /c echo @path was changed 30 days ago”
/D -30
List the size of all .doc files:
C:\> FORFILES /S /M *.doc /C “cmd /c echo @fsize”
An alternative method of dealing with files older or newer than a
specified date is to use ROBOCOPY
FORMAT.com
Format a disk for use with Windows.
Syntax
FORMAT drive: [/FS:file-system] [/V:label] [/Q] [size] [/C]
Key
/FS:file-system The file system (FAT or NTFS).
The NTFS file system does not function on floppy disks.
/V:label The volume label.
/Q Quick format.
/C Compression - files added to the new disk will be compressed.
[size] may be defined either with /F:size or /A:size
/F:size size is the size of the floppy disk (720, 1.2, 1.44, 2.88, or 20.8).
/A:size Allocation unit size.
Default settings (via /F) are strongly recommended for general use.
NTFS supports 512, 1024, 2048, 4096, 8192, 16K, 32K, 64K.
FAT supports 8192, 16K, 32K, 64K, 128K, 256K.
NTFS compression is not supported for allocation units above 4096.
Example
@echo off
Echo Warning this will reformat the entire D: disk!
PAUSE
format D: /FS:NTFS /x
FSUTIL.exe
File and Volume specific commands, Hardlink management, Quota
management, USN, Sparse file, Object ID and Reparse point management
Create a hardlink
FSUTIL hardlink create new_filename existing_filename
Eg : fsutil hardlink create c:\foo.txt c:\bar.txt
QUOTA Management
FSUTIL quota {query|disable|track|enforce } C:
FSUTIL quota violations
FSUTIL quota modify volume_pathname threshold limit user
Eg : fsutil quota modify c: 3000 5000 domain\user
Bugs
FSUTIL outputs a NULL character (not a space) after every drive
specifier, this may cause difficulty when piping the output of fsutil into other
commands (particularly FOR), see this forum thread for more detail.
Some features in fsutil are reported to not work correctly under FAT or
FAT32 volumes e.g. FSUTIL dirty query.
FTP
File Transfer Protocol
Syntax
FTP [-options] [-s:filename] [-w:buffer] [host]
key
-s:filename Run a text file containing FTP commands.
host Host name or IP address of the remote host.
-g Disable filename wildcards.
-n No auto-login.
-i No interactive prompts during ftp.
-v Hide remote server responses.
-w:buffer Set buffer size to buffer
(default=4096)
-d Debug
-a Use any local interface when binding data connection.
Commands to run at the FTP: prompt
append local-file [remote-file]
Append a local file to a file on the remote computer.
ascii Set the file transfer type to ASCII, the default.
In ASCII text mode, character-set and end-of-line
characters are converted as necessary.
bell Toggle a bell to ring after each command.
By default, the bell is off.
binary Set the file transfer type to binary.
Examples
an example FTP Script to retrieve files in binary and then ascii mode:
::GetFiles.ftp
[User_id]
[ftp_password]
binary
get /usr/file1.exe
get file2.html
mget *.jpeg
ascii
mget *.txt
quit
FTYPE
Display or change the link between a FileType and an executable
program
Syntax
FTYPE fileType=executable_path
FTYPE
FTYPE fileType
FTYPE fileType=
Key
fileType : The type of file
executable_path : The executable program including any command line parameters
More than one file extension may be associated with the same File Type.
e.g. both the extension .JPG and the extension .JPEG may be associated with
the File Type “jpegfile”
File Types can be displayed in the Windows Explorer GUI under Options,
File Types however the naming used is not consistent e.g. the File Type
“txtfile” is displayed in the GUI as “Text Document”and “jpegfile” is
displayed as “image/jpeg”
FTYPE filetype will display the current executable program for that file type
e.g. FTYPE jpegfile.
FTYPE without any parameters will display all FileTypes and the executable
program for each.
Command line parameters are exactly like batch file parameters, %0 is the
executable program and %1 will reference the document filename
so a simple command line might be:
MyApplication.exe “%1”
If any further parameters are required by the application they can be passed as
%2, %3. To pass ALL parameters to an application use %*. To pass all the
remaining parameters starting with the nth parameter, use %~n where n is
between 2 and 9.
For example:
FTYPE pagemill.html=C:\PROGRA~1\Adobe\PAGEMI~1.0\PageMill.exe
“%1”
ASSOC .html=pagemill.html
If you have multiple applications that use the same file extension, the ASSOC
command can be used to switch the file extension between the different
FileTypes.
Deleting a FileType
If you have a file association between .DOC and Word for Windows then at a
command prompt you can open a document with any of the following
commands:
note that the file extension must be supplied for this to work
GLOBAL (*)
Display membership of global groups on remote servers or remote
domains.
Syntax
GLOBAL group_name domain_name | \server
Key
Examples:
GLOBAL “Domain Users” Scotland
Displays the members of the group “Domain Users” in the Scotland domain.
GOTO
Direct a batch program to jump to a labelled line.
Syntax
GOTO label
Key
label : a predefined label in the batch program. Each label must
be on a line by itself, beginning with a colon.
To exit a batch script file or exit a subroutine specify GOTO:eof this will
transfer control to the end of the current batch file, or the end of the current
subroutine.
Examples:
:MySubroutine
Echo the input was 12
goto:eof
:s_routine_0
Echo You typed Y for yes
goto:eof
:s_routine_1
Echo You typed N for no
goto:eof
In this example the COPY command will only run if the parameter “Update”
is supplied to the batch
@echo off
setlocal
IF /I NOT %1==Update SET _skip=::
GPUPDATE.exe
Update Group Policy settings.
Syntax
GPUpdate [/Force] [/Logoff] [/Boot] [/Sync]
[/Target:{Computer | User}] [/Wait:value]
Key:
/Force Apply all policy settings, not just those that have changed.
/Logoff Logoff after the Group Policy settings have been updated.
Some group policy client-side extensions are only processed when a
user logs on. (Software Install, Folder Redirection.)
/Boot Restart after the Group Policy settings are applied.
Some group policy client-side extensions are only processed at startup
(e.g. computer-targeted Software Install)
/Sync Apply the next foreground policy synchronously (in the background).
This can be applied to computer boot and/or user logon. (see /Target)
/Target: Update only User or only Computer policy settings
default = both
/Wait: The number of seconds to wait for policy processing.
default = 600 (10 minutes)
‘0’ = do not wait.
‘-1’ = wait indefinitely.
If the time limit is exceeded, the command prompt returns,
but policy processing continues.
HELP
Online help for MS Windows - most commands will give help when run
with /? or -? (COMMAND /? or COMMAND -?)
GUI Help is available from START - Help or by running the help files
directly:
C:\WINDOWS\help\ntcmds.chm
C:\WINDOWS\help\ntdef.chm
C:\WINDOWS\help\ntchowto.chm
C:\WINDOWS\help\nthelp.chm
C:\WINDOWS\help\ntshared.chm
Syntax
WINHELP [options] helpfile.hlp
WINHLP32.exe [options] helpFile
In XP: C:\WINDOWS\PCHealth\HelpCtr\Binaries\HelpCtr.exe
options:
-H show help about help
-G[n] Build a .gid file and quit,
If a number is specified, it determines which extensible tab to
display by default the first time the help file is opened.
A value of 1 would be the first tab beyond the Find tab.
This command cannot be used with -S.
-S Create a .gid file without showing an animated icon.
Cannot be used with -G. (winhlp32 only)
-W window
Specify the window for displaying the topic.
This command cannot be used with -P.
-P Show the topic in a pop-up window.
This command cannot be used with -W.
You must use the -P switch in combination with the
-N (context number) or -I (topic ID) switch.
-N contextNum | -I topicID
Specify the topic to open using either a topic number,
(defined in the [MAP] section of the HPJ file.)
or a topic ID string
(# footnote in the topic).
-K keyword
Specify the topic to open using a keyword.
This command cannot be used with -N or -I.
A Directory Inheritance option for the integrity ACE may precede the level:
/inheritance:e|d|r
e - enable inheritance
d - disable inheritance and copy the ACEs
r - remove all inherited ACEs
user A user account, Group or a SID
/restore Apply the acls stored in ACLfile to the files in directory
permission is a permission mask and can be specified in one of two forms:
a sequence of simple rights:
F - full access
M - modify access
RX - read and execute access
R - read-only access
W - write-only access
a comma-separated list in parenthesis of specific rights:
D - delete
RC - read control
WDAC - write DAC
WO - write owner
S - synchronize
AS - access system security
MA - maximum allowed
GR - generic read
GW - generic write
GE - generic execute
GA - generic all
RD - read data/list directory
WD - write data/add file
AD - append data/add subdirectory
REA - read extended attributes
WEA - write extended attributes
X - execute/traverse
DC - delete child
RA - read attributes
WA - write attributes
inheritance rights may precede either form and are applied
only to directories:
(OI) - object inherit
(CI) - container inherit
(IO) - inherit only
(NP) - don’t propagate inherit
Using iCACLS
To edit a file you must already have the “Change” ACL (or be the
file’s owner)
To use the iCACLS command to change the permissions of a file
requires “FULL Control” (or be the file’s owner)
File “Ownership” will always override all ACL’s - you always have
Full Control over files that you create.
Inherited folder permissions are displayed as:
OI - Object inherit - This folder and files. (no inheritance to subfolders)
CI - Container inherit - This folder and subfolders.
IO - Inherit only - The ACE does not apply to the current file/directory
These can also be combined as folllows:
IF
Conditionally perform a command.
File syntax
IF [NOT] EXIST filename command
IF [NOT] EXIST filename (command) ELSE (command)
String syntax
IF [/I] [NOT] item1==item2 command
IF [/I] item1 compare-op item2 command
IF [/I] item1 compare-op item2 (command) ELSE (command)
Error Check Syntax
IF [NOT] DEFINED variable command
IF [NOT] ERRORLEVEL number command
IF CMDEXTVERSION number command
key
item May be a text string or an environment variable
a variable may be modified using either
Substring syntax or Search syntax
command The command to perform
NOT perform the command if the condition is false.
== perform the command if the two strings are equal.
/I Do a case Insensitive string comparison.
compare-op May be one of
EQU : Equal
NEQ : Not equal
LSS : Less than <
LEQ : Less than or Equal <=
GTR : Greater than >
GEQ : Greater than or equal >=
This 3 digit syntax is necessary because the > and <
symbols are recognised as redirection operators
Examples:
IF EXIST C:\install.log (echo complete) ELSE (echo failed)
IF DEFINED _department ECHO Got the department variable
IF DEFINED _commission SET /A _salary=%_salary% + %_commission%
IF CMDEXTVERSION 1 GOTO start_process
IF %ERRORLEVEL% EQU 2 goto sub_problem2
Does %1 exist?
To test for the existence of a command line parameter - use empty brackets
like this
In the case of a variable that may be NULL - a null variable will remove the
variable definition altogether, so testing for NULLs becomes easy:
IF DEFINED will return true if the variable contains any value (even if the
value is just a space)
Test the existence of files and folders
IF EXIST name - will detect the existence of a file or a folder - the script
empty.cmd will show if the folder is empty or not.
Brackets
You can improve the readability of a batch script by writing a complex IF…
ELSE command over several lines using brackets
e.g.
IF EXIST filename (
del filename
) ELSE (
echo The file was not found.
)
The IF statement does not use any great intelligence when evaluating
Brackets, so for example the command below will fail:
IF EXIST MyFile.txt (ECHO Some(more)Potatoes)
This version will work:
IF EXIST MyFile.txt (ECHO Some[more]Potatoes)
If the string being compared by an IF command includes delimiters such
as [Space] or [Comma], then either the delimiters must be escaped with a
caret ^ or the whole string must be “quoted”.
This is so that the IF statement will treat the string as a single item and not as
several separate strings.
Testing Numeric values
Do not use brackets or quotes when comparing numeric values
e.g.
IF (2) GEQ (15) echo “bigger”
or
IF “2” GEQ “15” echo “bigger”
These will perform a character comparison and will always echo “bigger”
however the command
IF 2 GEQ 15 echo “bigger”
Will perform a numeric comparison and works as expected - notice that this
behaviour is exactly opposite to the SET /a command where quotes are
required.
The examples here all use GEQ, but this applies equally to all the
compare-op operators: EQU, NEQ, LSS, LEQ, GTR, GEQ
when comparing numbers as a string “026” > “26”
Wildcards
Wildcards are not supported by IF, so %COMPUTERNAME%==SS6*
will not match EXAMPLE
IFMEMBER (*)
Find out if the current user is a member of one or more workgroups.
Syntax
IFMEMBER [options] WorkGroup [ WorkGroup2 WorkGroup3…]
Options:
/verbose or /v : print all matches.
/list or /l : print all groups user is a member of
Examples
IFMEMBER /v /l “MyDomain\Administrators”
IF ERRORLEVEL 1 echo This user is an Administrator
Notice that the syntax here is the opposite to most other commands in that an
%errorlevel% of 1 = Success
IPCONFIG
Configure IP (internet protocol configuration)
Syntax
IPCONFIG /all Display full configuration information.
IPCONFIG /release [adapter]
Release the IP address for the specified adapter.
IPCONFIG /renew [adapter]
Renew the IP address for the specified adapter.
IPCONFIG /flushdns Purge the DNS Resolver cache.
IPCONFIG /registerdns Refresh all DHCP leases and re-register DNS names.
IPCONFIG /displaydns Display the contents of the DNS Resolver Cache.
IPCONFIG /showclassid adapter
Display all the DHCP class IDs allowed for adapter.
IPCONFIG /setclassid adapter [classid]
Modify the dhcp class id.
The default is to display only the IP address, subnet mask and default gateway
for each adapter bound to TCP/IP.
For Release and Renew, if no adapter name is specified, then the IP address
leases for all adapters bound to TCP/IP will be released or renewed.
Note: Kill -f basically just nukes the process from existence, potentially
leaking a lot of memory and losing any data that the process hadn’t
committed to disk yet. It is there for worst case scenarios - when you
absolutely must end the process now, and don’t care whether proper cleanup
gets done or not.
LABEL
Edit a disk label.
Syntax
LABEL [drive:][label]
The disk label is never referred to by other batch commands, it’s just for
human recognition.
e.g. as a reminder of which floppy disk is actually in the machine.
The maximum length is 11 characters (spaces allowed)
This is not to be confused with the drive description held in the registry.
Example
LOCAL (*)
Display membership of local groups on remote servers or remote
domains.
Syntax
LOCAL group_name domain_name | \server
Key
Examples:
Displays the members of the group ‘Power Users’ in the Scotland domain.
LOGEVENT (*)
Write text to the event log (event viewer)
Syntax
logevent [-m \MachineName] [options] “Event Text”
Options
-s Severity one of
(S)uccess
(I)nformation
(W)arning
(E)rror
(F)ailure
-c Category A Number between 0 and 65536
This can be used to Filter the event log view
(default = “none”)
LOGMAN.exe
Manage Performance Monitor & performance logs from the command
line.
Syntax
logman [create|query|start|stop|delete|update|import|export] [options]
Verbs:
create Create a new data collector.
query Query data collector properties.
If no name is given all data collectors are listed.
start Start an existing data collector and set the begin time to manual.
stop Stop an existing data collector and set the end time to manual.
delete Delete an existing data collector.
update Update an existing data collector’s properties.
import Import a data collector set from an XML file.
export Export a data collector set to an XML file.
Adverbs:
counter Create a counter data collector.
trace Create a trace data collector.
alert Create an alert data collector.
cfg Create a configuration data collector.
providers Show registered providers.
Options (counter):
-c path [path […]]
The performance counters to collect.
To collect remotely, prefix with the \machine name.
-cf filename File listing performance counters to collect,one per line.
-f {bin|bincirc|csv|tsv|sql}
The log format for the data collector. For SQL database format,
you must use the -o option in the command line with the DNS!log option.
The defaults is binary.
-sc value Maximum number of samples to collect with a performance counter data collector.
-si [[hh:]mm:]ss Sample interval for performance counter data collectors.
Options (trace):
-f {bin|bincirc|csv|tsv|sql}
The log format for the data collector. For SQL database format,
you must use the -o option in the command line with the DNS!log option.
The defaults is binary.
-mode trace_mode Event Trace Session logger mode.
-ct {perf|system|cycle}
The clock resolution to use when logging the time stamp for
each event: query performance counter, system time, or CPU cycle.
-ln logger_name Logger name for Event Trace Sessions.
-ft [[hh:]mm:]ss Event Trace Session flush timer.
-[-]p provider [flags [level]]
A single Event Trace provider to enable.
The terms ‘Flags’ and ‘Keywords’ are synonymous in this context.
-pf filename File listing multiple Event Trace providers to enable.
-[-]rt Run the Event Trace Session in real-time mode.
-[-]ul Run the Event Trace Session in user mode.
-bs value Event Trace Session buffer size in kb.
-nb min max Number of Event Trace Session buffers.
Options (alert):
-[-]el Enable/Disable event log reporting.
-th threshold [threshold […]]
Specify counters and a threshold values for an alert.
-[-]rdcs name Data collector set to start when alert fires.
-[-]tn task Task to run when alert fires.
-[-]targ argument Task arguments.
-si [[hh:]mm:]ss Sample interval for performance counter data collectors.
Options (cfg):
-[-]ni Enable/Disable network interface query.
-reg path [path […]] Registry values to collect.
-mgt query [query […]] WMI objects to collect.
-ftc path [path […]] Full path to the files to collect.
Options:
-? Display context sensitive help.
-s computer Perform the command on specified remote system.
-config filename Settings file containing command options.
[-n] name Name of the target object.
-pid pid Process identifier.
-xml filename Name of the XML file to import or export.
-as Perform the requested operation asynchronously.
-[-]u user [password] User to Run As. Entering a * for the password produces a prompt
The interactive password is not displayed on screen.
-m [start] [stop] Change to manual start or stop instead of a scheduled begin or end time.
-rf [[hh:]mm:]ss Run the data collector for the specified period of time.
-b dd/MM/yyyy HH:mm:ss[AM|PM] Begin the data collector at specified time.
-e dd/MM/yyyy HH:mm:ss[AM|PM] End the data collector at specified time.
-[-]r Repeat the data collector daily at the specified begin and end times.
-o {path|dsn!log} Path of the output log file or the DSN and log set name in a
SQL database. The default path is ‘%systemdrive%\PerfLogs\Admin’.
-[-]a Append to an existing log file.
-[-]ow Overwrite an existing log file.
-[-]v {nnnnnn | mmddhhmm} Attach file versioning information to the end of the log name.
-[-]rc task Run the command specified each time the log is closed.
-[-]max value Maximum log file size in MB or number of records for SQL logs.
-[-]cnf [[hh:]mm:]ss Create a new file when the specified time has elapsed or when the max size is
exceeded.
-y Answer yes to all questions without prompting.
-fd Flush all the active buffers of an existing Event Trace Session to disk.
-ets Send commands to Event Trace Sessions directly without saving or scheduling.
Note: Where [-] is listed, an extra - negates the option. For example —u
turns off the -u option.
This page describes the Windows 7/2008 version of Logman, the XP
version only supports the Counter and Trace Adverbs (no Alerts/thresholds).
Examples:
Create a counter to Log the % Processor Time on the local machine:
C:\> set _mycounters=”\Processor(_Total)\% Processor Time”
C:\> set _mylogfile=C:\docs\example.blg
C:\> Logman.exe create counter example-CPU -f bincirc -v mmddhhmm -
max 250 -c %_mycounters% -o %_mylogfile%
Start the counter running (and then run whatever other process you wish
to monitor):
C:\> Logman.exe start example-CPU
LOGTIME.exe (*)
Create logtime.txt and adds the date, time and a message
Syntax
LOGTIME text_string
Key
text_string : The message to add to the log file.
An alternative command is
ECHO. | DATE | FIND /i “current”>>C:\Install_log.txt
LOGOFF.exe (*)
Log a user off.
Syntax
LOGOFF [/f] [/n]
Key
/f Force running processes to close, but will ask for user confirmation.
The user will not be asked to save unsaved data.
/n Force running processes to close without confirmation.
The user will be prompted to save unsaved data.
By default LOGOFF will ask for user confirmation and prompt to save
unsaved data.
Windows security log events
Logon Event IDs 528 and 540 = successful logon
Logoff Event ID 538 = logoff
Logon and logoff events also specify a Logon Type code:
Logon Type 2 – Interactive - Log on at the local keyboard / screen (see
the event description for a computer name).
Logon Type 3 – Network - connections to shared folders or printers,
over-the-network logons, IIS logons( but not basic authentication)
Logon Type 4 – Batch - The Scheduled Task service creates a new logon
session for each task.
Logon Type 5 – Service - Each service is configured to run as a specified
user account.
Logon Type 7 – Unlock- a password protected screen saver.
Logon Type 8 – NetworkCleartext - a network logon like logon type 3
but where the password was sent over the network in clear text.
Logon Type 9 – NewCredentials - If you use RunAs /netonly and records
the logon event with logon type 2.
Logon Type 10 – RemoteInteractive - Terminal Services, Remote
Desktop or Remote Assistance.
Logon Type 11 – CachedInteractive - mobile users not connected to the
network connecting with cached credentials.
MBSACLI
Baseline Security Analyzer.
Syntax
mbsacli [/c|/i|/r|/d domainname|ipaddress|ipaddressrange]
[/n option] [/sus SUS server|SUS filename]
[/s level] [/nosum] [/nvc] [/o filename] [/e] [/l] [/ls]
[/lr report name] [/ld report name] [/v] [/?]
[/qp] [/qe] [/qr] [/q] [/f] [/unicode]
Options
The Computer to Scan:
/sus SUS server | SUS filename - Check only for security updates that are approved
at the specified SUS server, or at the file path of the Approveditems.txt file.
e.g. http://server or http://server/Approveditems.txt.
If neither is specified, the value will default from the registry (set via Group Policy)
/o filename By default, the output filename uses the format “domain - computername
(date)”
Display the Results
/? - Usage help.
MEM
Display memory usage.
Syntax
MEM
MEM /C
MEM /D
MEM /P
Key
/P List programs in memory
with the memory address and size of each
/D List Programs(as /P) and also Devices
/C List programs in conventional memory and
list programs in upper memory
MEM will only display details about the current CMD shell
environment, programs running in a separate shell (or WIN32 programs) will
not be listed - so it won’t tell you anything about total memory usage.
MD
Make Directory - Creates a new folder.
Syntax
MD [drive:]path
Key
The path can consist of any valid characters up to the maximum path length available
You should avoid using the following characters in folder names - they
are known to cause problems
© ® ” - & ‘ ^ ( ) and @
Folder names are not case sensitive, but only folder names longer than 8
characters will always retain their case, as typed.
For Example
C:\temp> MD MyFolder
will create
C:\temp\Alpha\
C:\temp\Beta\
C:\temp\Gamma\
for long filenames include quotes
MD “\utils\downloads\Super New Editor”
You cannot create a folder with the same name as any of the following
devices:
CON, PRN, LPT1, LPT2 ..LPT9, COM1, COM2 ..COM9
This limitation ensures that redirection to these devices will always work.
If you plan to copy data onto CDROM avoid folder trees more than 8 folders
deep
MODE
Mode is an all purpose configuration command, used without
parameters, MODE displays the status of all devices installed on your system.
Devices
Show the status of all devices: (Typically COM1, COM2, LPT1, CON)
MODE
Keyboard
Set the keyboard typematic rate, the rate at which a character is repeated
when you hold down the key.
MODE CON[:] [RATE=r DELAY=d]
Printing
To redirect output from a parallel port (PRN, LPT1, LPT2, or LPT3) to a
serial port(COM1, COM2, COM3, etc).
You must be a member of the Administrators group to redirect printing.
To setup the parameters for a serial port (* see Start, Help, Commands for
more on this).
MODE COMm [options*]
International Settings
MORE
Display output one screen at a time. MORE can be used to run any
executable command (or batch file) and pause the screen output one screen at
a time. MORE can also be used to TYPE the contents of any file to the
screen.
Syntax
command | MORE [/E [/C] [/P] [/S] [/Tn] [+n]]
MORE [/E [/C] [/P] [/S] [/Tn] [+n]] < Pathname
MORE /E [/C] [/P] [/S] [/Tn] [+n] [Pathname(s)]
Key
command : Any executable command or batch file
Pathname : The file to be displayed. (if more than one separate with spaces)
/E : Enable extended features
/E /C : Clear screen before displaying page
/E /P : Expand FormFeed characters
/E /S : Squeeze multiple blank lines into a single line
/E /Tn : Expand tabs to n spaces (default 8)
/E +n : Start displaying the first file at line n
You can create an environment variable called %MORE% and use this to
supply any of the above switches.
When MORE is used without any redirection symbols it will display the %
complete e.g.
MORE /E myfile.txt
—More (17%) —
If extended features are enabled, (/E) the following keystrokes can be used at
the — More — prompt:
<space> Display next page
<return> Display next line
Q Quit
P n Display next n lines
S n Skip next n lines
F Display next file
= Show line number
? Show help line
MOUNTVOL (Windows
2000/2003/Server 2008)
Link volumes without requiring a drive letter. Create, delete or list a
volume mount point. NTFS junction mount points can only be used with local
NTFS directories, (unlike DFS junction points which will target a network
share). MOUNTVOL can be found on the Windows CD i386 folder.
Syntax
MOUNTVOL [drive:]path option
Options
path : An existing NTFS folder where the mount point will reside.
VolName : The volume name that is the target of the mount point.
In the form \?\Volume{GUID}\, where {GUID} is a globally unique identifier
e.g. \?\Volume\{2eca078d-5cbc-43d3-aff8-7e8511f60d0e}\
/D : Remove the volume mount point from the specified folder.
/E : Re-enable automatic mounting of new basic volumes (2003 and above).
/L : List the mounted volume name for the specified folder.
/s : Itanium-based computers only. Mount the EFI System Partition on the specified drive.
/p : Remove the volume mount point from the specified directory,
dismount the basic volume, and take the basic volume offline,
making it unmountable. (Server 2008)
The GUID is used to identify a unique volume even if the drive letter
changes.
If other processes are using the volume, mountvol closes any open
handles before dismounting the volume.
Volumes that are dismounted by using /p are listed in the volumes list as
“NOT MOUNTED UNTIL A VOLUME MOUNT POINT IS CREATED.”
If the volume has more than one mount point, use /d to remove the additional
mount points before using /p. You can make the basic volume mountable
again by assigning a volume mount point.
If you need to expand your volume space without reformatting or
replacing a hard drive, you can add a mount path to another volume. The
benefit of using one volume with several mount paths is that you can access
all local volumes by using a single drive letter (such as C:). You do not need
to remember which volume corresponds to which drive letter—although you
can still mount local volumes and assign them drive letters.
When using junction points:
• Use NTFS ACLs to protect junction points from inadvertent deletion.
• Use NTFS ACLs to protect files and directories that are targeted by junction
points from inadvertent deletion or other file system operations.
• Never delete a junction point by using Explorer, a del /s command, or other
file system utilities that walk recursively into directory trees. These utilities
affect the target directory and all subdirectories.
• Use caution when you apply ACLs or change file compression in a directory
tree that includes NTFS junction points.
• Do not create namespace cycles with NTFS or DFS junction points.
• Put all your junction points in a secure location in a namespace where you
can test them out in safety, and where other users will not mistakenly delete
them or walk through them.
Examples
List the available volumes on your system (this will list the GUIDs)
C:\> mountvol
Create a mount point called example
C:\> md example
C:\> mountvol example \?\Volume\{2eca078d-5cbc-43d3-aff8-
7e8511f60d0e}\
Delete the mount point
C:\> mountvol \?\Volume\{2eca078d-5cbc-43d3-aff8-7e8511f60d0e}\ /d
MOVEUSER.exe (*)
Move a local user account into a domain or move a user account between
machines.
Syntax
MOVEUSER [DOMAIN/]user1 [DOMAIN/]user2 [/c:computer] [/k] [/y]
Key:
user1 The existing user (who has a local profile)
Specify domain users in ‘DOMAIN/user’ format
or just ‘user’ for a local account.
user2 The user acount that will inherit the user1 profile.
This account must already exist.
Specify domain users in DOMAIN/user format
specify only user for local accounts.
/c:computer The computer on which to make the changes.
/k Keep user account user1 (only applies to local users)
/y Overwrite an existing profile for user2.
MSG.exe
Send a pop-up message to a user. The ‘Home’ editions of Windows don’t
include MSG.
Syntax
MSG username [options] [message]
MSG sessionname [options] [message]
MSG sessionid [options] [message]
MSG @filename [options] [message]
MSG * [options] [message]
Options
/SERVER:servername The server to contact (default is current).
/TIME:seconds Time delay to wait for receiver to acknowledge msg.
/V Verbose, display extra information.
/W Wait for response from user, useful with /V.
If no message text to send is specified, MSG will prompt for it
(also reads from stdin)
@filename identifies a file containing a list of usernames,
sessionnames or sessionids to send the message to.
* will send the message to all sessions on the server.
e.g. use this for Terminal Server/Citrix shutdown messages.
MSIEXEC
Microsoft Windows Installer.
Syntax
Install
MSIEXEC /i package options
Uninstall
MSIEXEC /x package options
Advertise to current user
MSIEXEC /ju package options [/t Transform_List | /g LanguageID]
Advertise to all users
MSIEXEC /jm package options [/t Transform_List | /g LanguageID]
Administrative install - install on the network.
MSIEXEC /a package
Apply a patch to an installed Admin image
MSIEXEC /p patchPKG /a package
Options:
/fp fix - replace missing files
/fo fix - replace Older files
/fe fix - replace older or Equal date files
/fd fix - replace Different version files
/fc fix - replace files based on Checksum differences
/fa fix - replace All files
/fu fix - rewrite HKCU registry
/fm fix - rewrite HKLM registry
/fs fix - recreate shortcuts
/fv fix - rewrite local cache from source
/l* Logfile Log Everything (not Verbose)
/l*v Logfile Log Everything Verbose
/lv Logfile Log Verbose
/le Logfile Log All error messages
/lw Logfile Log Non-fatal warnings
/li Logfile Log Status messages
/la Logfile Log Startup actions
/lr Logfile Log Actions
/lu Logfile Log User requests
/lc Logfile Log User Interface (UI) parameters
/lm Logfile Log memory use
/lp Logfile Log Terminal properties
/l+ Logfile Append to an existing log file.
/l! Logfile Clear an existing log file.
/q , /qn No UI.
/qb Basic UI.
/qb! Basic UI with no cancel button.
/qr Reduced UI. A modal dialog box is displayed at the end of the install.
/qf Full UI. A modal dialog box is displayed at the end of the install.
/qn+ No UI. However, a modal dialog box is displayed at the end of the installation.
/qb+ Basic UI. A modal dialog box is displayed at the end of the installation. If you cancel the
installation, a modal dialog box is not displayed.
/qb- Basic UI with no modal dialog boxes.
/y module Register a DLL - only use for registry information that cannot be added using the registry
tables of the .msi file.
/z module UnRegister a DLL - only use for registry information that cannot be removed using the
registry tables of the .msi file.
MSINFO32.exe
System Information - details about hardware configuration, computer
components, software and drivers.
Syntax
MSinfo32 options
Options
/nfo PathName Save the information as a .nfo file.
An .nfo file name extension will be appended to the name if needed.
/pch Display History View •
/report PathName
Output a text file.
/computer Get details from a remote computer.
/categories Display or output the specified categories.
/category Set focus to a specific category at startup •
/showcategories
Start System Information with the category IDs displayed
instead of the friendly names or the localized names. •
For example, when you use this switch, the Software Environment
category is displayed as the SWEnv category.
SWEnv is a valid categoryID argument for the /category switch
and the /categories switch.
• = supported in Windows XP only
If no options are specified the GUI interface will open.
MSinfo is typically started from Help | About rather than the command
line, it is not normally in the system path, but can usually be found in:
C:\Program Files\Common Files\Microsoft Shared\MSInfo\
Generation of the text file can take some time, depending on the complexity
of the system.
If you have problems getting MSInfo to run, check permissions on the
following key: HKLM\SOFTWARE\Microsoft\Shared Tools\MSInfo\
MSTSC
Terminal Server Connection, RDP (Remote Desktop Protocol)
Syntax
MSTSC option
MSTSC /Edit”ConnectionFile”
MSTSC /migrate
Options
ConnectionFile The name of an RDP file for connection
/v:<server[:port]> The remote computer to connect to
/console Connect to the console of a server (NT/XP)
/Admin Connect to a session for administering the server(Vista/2008)
/f Start in Full Screen mode
/w:width Width of the RDP screen
/h:height Height of the RDP screen
/span Match the Remote Desktop width and height with the local virtual
desktop, spanning across multiple monitors if necessary.(Vista/2008)
/public Run Remote Desktop in public mode. (Vista/2008)
In public mode, passwords and bitmaps are not cached.
/edit Open the RDP file for editing.
/migrate Convert a legacy Client connection file into an .RDP file
The /d option is not available with the posix version of mv, but if you prefer,
you can do a file replace at boot time by manually updating the registry
(which is all MV.exe does)
Double click on
PendingFileRenameOperations
(if it does not exist - create of type multi_str )
On the first line is the name of the new file with \??\ in front,
e.g.
\??\d:\temp\ntfs.sys
Click OK
So the complete Multi-String Data would appear like:
\??\d:\temp\ntfs.sys
!\??\c:\winnt\system32\drivers\ntfs.sys
NET.exe
The NET Command is used to manage network resources as follows:
Manage Services
NET START, STOP, PAUSE, CONTINUE
Security
NET ACCOUNTS, USER, GROUP, LOCALGROUP
Network Messaging
NET NAME, SEND
Help
NET HELP, HELPMSG
Network configuration
NET COMPUTER, CONFIG_WORKSTATION, CONFIG_SERVER,
STATISTICS_WORKSTATION, STATISTICS_SERVER
When you use NET commands in a batch file, you can use the Y or N switch
to unconditionally answer Yes or No to questions returned by the Net
command
Only use the version of netdom supplied for your operating system, an
older version of the NETDOM utility is included with the Windows XP
Support Tools. This command is known to cause bugs in Vista & Windows 7
= add - Add a configuration entry to a list of entries.
netsh add helper - Install the specified helper DLL
= advfirewall - Change the ‘netsh advfirewall’ context.
netsh advfirewall consec ? - Display a list of commands.
netsh advfirewall consec add - Add a new connection security rule.
netsh advfirewall consec delete - Delete all matching connection security rules.
netsh advfirewall consec dump - Display a configuration script.
netsh advfirewall consec set - Set new values for properties of an existing rule.
netsh advfirewall consec show - Display a specified connection security rule.
netsh advfirewall dump Create a script that contains the current configuration.
If saved to a file, this can be used to restore the configuration settings.
netsh advfirewall export path\filename - Export the current policy to the specified file.
netsh advfirewall import path\filename - Import policy from the specified file.
netsh advfirewall firewall add - Add a new inbound or outbound firewall rule.
netsh advfirewall firewall delete - Delete all matching inbound rules.
netsh advfirewall firewall dump - Display a configuration script.
netsh advfirewall firewall set - Set new values for properties of a existing rule.
netsh advfirewall firewall show - Display a specified firewall rule.
netsh advfirewall monitor delete - Delete all matching security associations.
netsh advfirewall monitor dump - Display a configuration script.
netsh advfirewall monitor show - Show all matching security associations.
netsh advfirewall reset - Reset to factory settings (Firewall=ON)
netsh advfirewall set allprofiles - Set properties in all profiles.
netsh advfirewall set currentprofile - Set properties in the active profile.
netsh advfirewall set domainprofile - Set properties in the domain profile.
netsh advfirewall set global - Set the global properties.
netsh advfirewall set privateprofile - Set properties in the private profile.
netsh advfirewall set publicprofile - Set properties in the public profile.
netsh advfirewall show allprofiles - Display properties for all profiles.
netsh advfirewall show currentprofile - Display properties for the active profile.
netsh advfirewall show domainprofile - Display properties for the domain properties.
netsh advfirewall show global - Display the global properties.
netsh advfirewall show privateprofile - Display properties for the private profile.
netsh advfirewall show publicprofile - Display properties for the public profile.
netsh advfirewall show store - Display the policy store for the current interactive session.
=bridge - Change to the ‘netsh bridge’ context.
netsh bridge dump - Display a configuration script.
netsh bridge install - Install the component corresponding to the current context.
netsh bridge set - Set configuration information.
netsh bridge show - Display information.
netsh bridge uninstall - Remove the component corresponding to the current context.
=delete - Delete a configuration entry from a list of entries.
netsh delete helper Remove the specified helper DLL from netsh.
Note that after a helper is removed, it is no longer supported by netsh.
=dhcpclient - Change to the ‘netsh dhcpclient’ context.
netsh dhcpclient list - List all the commands available.
netsh dhcpclient trace enable - Enable tracing for DHCP client and DHCP QEC.
netsh dhcpclient trace disable - Disable tracing for DHCP client and DHCP QEC.
=dump - Display a configuration script.
netsh dump - Create a script that contains the current configuration.
If saved to a file, this can be used to restore the configuration settings.
=exec - Run a script file.
exec - Load a script file and run it.
=firewall - Change to the ‘netsh firewall’ context.
netsh firewall add - Add firewall configuration.
netsh firewall delete - Delete firewall configuration.
netsh firewall dump - Display a configuration script.
netsh firewall reset - Reset firewall configuration to default.
netsh firewall set allowedprogram - Set firewall allowed program configuration.
netsh firewall set icmpsetting - Set firewall ICMP configuration.
netsh firewall set logging - Set firewall logging configuration.
netsh firewall set multicastbroadcastresponse - Set firewall multicast/broadcast response
configuration.
netsh firewall set notifications - Set firewall notification configuration.
netsh firewall set opmode - Set firewall operational configuration.
netsh firewall set portopening - Set firewall port configuration.
netsh firewall set service - Set firewall service configuration.
netsh firewall show allowedprogram - Show firewall allowed program configuration.
netsh firewall show config - Show firewall configuration.
netsh firewall show currentprofile - Show current firewall profile.
netsh firewall show icmpsetting - Show firewall ICMP configuration.
netsh firewall show logging - Show firewall logging configuration.
netsh firewall show multicastbroadcastresponse - Show firewall multicast/broadcast response
configuration.
netsh firewall show notifications - Show firewall notification configuration.
netsh firewall show opmode - Show firewall operational configuration.
netsh firewall show portopening - Show firewall port configuration.
netsh firewall show service - Show firewall service configuration.
netsh firewall show state - Show current firewall state.
=help - Display a list of netsh commands.
netsh help
=http - Change to the ‘netsh http’ context.
netsh http add - Add a configuration entry to a table.
netsh http delete - Delete a configuration entry from a table.
netsh http dump - Display a configuration script.
netsh http flush - Flushe internal data.
netsh http show - Display information.
=interface - Change to the ‘netsh interface’ context.
netsh interface 6to4 + Change to the ‘netsh interface 6to4’ context.
netsh interface add - Add a configuration entry to a table.
netsh interface delete - Delete a configuration entry from a table.
netsh interface dump - Display a configuration script.
netsh interface ipv4 + Change to the ‘netsh interface ipv4’ context.
netsh interface ipv6 + Change to the ‘netsh interface ipv6’ context.
netsh interface isatap + Change to the ‘netsh interface isatap’ context.
netsh interface portproxy + Change to the ‘netsh interface portproxy’ context.
netsh interface reset - Reset information.
netsh interface set - Set configuration information.
netsh interface show - Display information.
netsh interface tcp + Change to the ‘netsh interface tcp’ context.
netsh interface teredo + Change to the ‘netsh interface teredo’ context.
The following sub-contexts are available:
6to4 ipv4 ipv6 isatap portproxy tcp teredo
=ipsec - Change to the ‘netsh ipsec’ context.
netsh ipsec dump - Display a configuration script.
netsh ipsec dynamic add - Add policy, filter, and actions to SPD.
netsh ipsec dynamic delete - Delete policy, filter, and actions from SPD.
netsh ipsec dynamic dump - Display a configuration script.
netsh ipsec dynamic set - Modifiy policy, filter, and actions in SPD.
netsh ipsec dynamic show - Display policy, filter, and actions from SPD.
netsh ipsec static add - Create new policies and related information.
netsh ipsec static delete - Delete policies and related information.
netsh ipsec static dump - Display a configuration script.
netsh ipsec static exportpolicy - Export all the policies from the policy store.
netsh ipsec static importpolicy - Import the policies from a file to the policy store.
netsh ipsec static set - Modify existing policies and related information.
netsh ipsec static show - Display details of policies and related information.
=lan - Change to the ‘netsh lan’ context.
netsh lan add - Add a configuration entry to a table.
netsh lan delete - Delete a configuration entry from a table.
netsh lan dump - Display a configuration script.
netsh lan export - Save LAN profiles to XML files.
netsh lan reconnect - Reconnect on an interface.
netsh lan set - Configure settings on interfaces.
netsh lan show - Display information.
=nap - Change to the ‘netsh nap’ context.
netsh nap client + Change to the ‘netsh nap client’ context.
netsh nap dump - Display a configuration script.
netsh nap hra + Change to the ‘netsh nap hra’ context.
netsh nap reset - Reset configuration.
netsh nap show - Show configuration and state information.
=netio - Change to the ‘netsh netio’ context.
netsh netio add - Add a configuration entry to a table.
netsh netio delete - Delete a configuration entry from a table.
netsh netio dump - Display a configuration script.
netsh netio show - Display information.
=ras - Change to the ‘netsh ras’ context. (Remote Access Server)
netsh ras aaaa - Change to the ‘netsh ras aaaa’ context.
netsh ras add - Add items to a table.
netsh ras delete - Remove items from a table.
netsh ras diagnostics - Change to the ‘netsh ras diagnostics’ context.
netsh ras dump - Display a configuration script.
netsh ras ip - Change to the ‘netsh ras ip’ context.
netsh ras ipv6 - Change to the ‘netsh ras ipv6’ context.
netsh ras set - Set configuration information.
netsh ras show - Display information.
=rpc - Change to the ‘netsh rpc’ context. (RPC firewall filter)
netsh rpc add - Create an Add list of subnets.
netsh rpc delete - Create a Delete list of subnets.
netsh rpc dump - Display a configuration script.
netsh rpc filter - Change to the ‘netsh rpc filter’ context.
netsh rpc reset - Reset the selective binding settings to ‘none’ (listen on all interfaces).
netsh rpc show - Display the selective binding state for each subnet on the system.
=set - Update configuration settings on a remote machine.
netsh set machine [name=] [user=][[DomainName\]UserName] [pwd=][Password | *]
If a machine name is not specified, the local machine is used.
A username and password cannot be used to connect to the local machine.
=show - Display information.
netsh show alias - List all defined aliases.
netsh show helper - List all the top-level helpers.
=winhttp - Change to the ‘netsh winhttp’ context.
netsh winhttp dump - Display a configuration script.
netsh winhttp import - Import WinHTTP proxy settings.
netsh winhttp reset - Reset WinHTTP settings.
netsh winhttp set - Configure WinHTTP settings.
netsh winhttp show - Display currents settings.
=winsock - Change to the ‘netsh winsock’ context.
netsh winsock audit - Display a list of Winsock LSPs that have been installed and removed.
netsh winsock dump - Display a configuration script.
netsh winsock remove - Remove a Winsock LSP from the system.
netsh winsock reset - Reset the Winsock Catalog to a clean state.
netsh winsock show - Display information.
netsh - Interactive mode
NBTSTAT.exe
Display protocol statistics and current TCP/IP connections using NBT
(NetBIOS over TCP/IP).
Syntax
By Name
NBTSTAT -a Remote_host_Name [options] [interval]
By IP address
NBTSTAT -A IP_address [options] [interval]
Key
-a (adapter status) List the remote machine’s name table given its name
-A (Adapter status) List the remote machine’s name table given its IP address
-c (cache) List NBT’s cache of remote [machine] names
and their IP addresses
-n (names) List local NetBIOS names.
-r (resolved) List names resolved by broadcast and via WINS
-R (Reload) Purge and reloads the remote cache name table
-S (Sessions) List sessions table with the destination IP addresses
-s (sessions) List sessions table converting destination IP
addresses to computer NETBIOS names.
-RR (ReleaseRefresh) Send Name Release packets to WINS and then, starts Refresh
interval Redisplay selected statistics, pausing interval seconds
between each display. Press Ctrl+C to stop redisplaying
statistics.
NETSTAT.exe
Display current TCP/IP network connections and protocol statistics.
Syntax
NETSTAT [options] [-p protocol] [interval]
Key
-a Display All connections and listening ports.
-e Display Ethernet statistics. (may be combined with -s)
-n Display addresses and port numbers in Numerical form.
-r Display the Routing table.
-o Display the Owning process ID associated with each connection.
-b Display the exe involved in creating each connection or listening port.*
-v Verbose - use in conjunction with -b, to display the sequence of
components involved for all executables.
-p protocol
Show only connections for the protocol specified;
may be any of: TCP, UDP, TCPv6 or UDPv6.
If used with the -s option then the following protocols
may also be specified: IP, IPv6, ICMP,or ICMPv6.
-s Display per-protocol statistics. By default, statistics are
shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPv6;
(The v6 protocols are not available under 2k and NT4)
The -p option may be used to display just a subset of these.
interval Redisplay statistics, pausing interval seconds between
each display. (default=once only) Press CTRL+C to stop.
* Where available this will display the sequence of components involved
in creating the connection or listening port. (Typically well-known
executables which host multiple independent components.) This option will
display the executable name in [ ] at the bottom, with the component it called
on top, repeated until TCP/IP is reached. The -b option can be time-
consuming and will fail unless you have sufficient permissions.
NOW.exe (*)
Display Message with current Date and Time
Syntax
NOW [message to be printed with time-stamp]
Typical output:
NTBACKUP
Backup to tape: drives, folders and the systemstate.
Syntax:
NTBACKUP backup [systemstate] “@bks file name”
/J {“job name“} [options] [/SNAP:{on|off}] [/um]
Options:
systemstate
Back up the System State data.
This will also force the backup type to normal or copy.
@bks file name
The name of the backup selection file (.bks file).
In 21st Century Windows Releases the at (@) character must precede this name.
A backup selection file contains information on the files and folders
to be backed up.
You have to create the file using the GUI version of NT Backup.
/J {“job name”}
The job name to be used in the log file
Describe the files and folders and the backup date-time.
/P {“pool name”}
The media pool from which you want to use media.
Usually a subpool of the Backup media pool, such as 4mm DDS.
If you select this you cannot use /A, /G, /F, or /T
/G {“guid name”}
Overwrite or append to this tape.
Don’t use with a media Pool (/P).
/T {“tape name”}
Overwrite or append to this tape.
Don’t use with a media Pool (/P).
/A
Perform an append operation.
Either “guid name” (/G) or “tape name” (/T) must be specified with this switch.
Don’t use with a media Pool (/P).
/N {“media name”}
The new tape name. Don’t use with Append (/A).
/F {“file name”}
Backup to a file - logical disk path and file name.
Do not use with the switches: /P /G /T.
/D {“set description”}
Label for each backup set
/DS {“server name”}
Back up the directory service file for MS Exchange 5.5 server.
This is not needed/does not work with Exchange 2000 since Exchange 2000
uses Active Directory.
/IS {“server name”}
Back up the Information Store file for an MS Exchange 5.5 Server.
/V:{yes|no}
Verify the data after the backup is complete.
/R:{yes|no}
Restrict access to this tape to the Owner/AdministratorS
/L:{f|s|n}
The type of log file: f=full, s=summary, n=none
/M {backup type}
The backup type. One of: normal, copy, differential, incremental, or daily
/RS:{yes|no}
Backs up the migrated data files located in Remote Storage.
The /RS command-line option is not required to back up the local Removable
Storage database (that contains the Remote Storage placeholder files).
When you backup the %systemroot% folder, Backup automatically backs up the
Removable Storage database as well.
/HC:{on|off}
Use hardware compression, if available, on the tape drive.
/SNAP:{on|off}
Copy open/locked files, requires XP or 2003,
creates a temporary snapshot for the volume shadow copy.
/um (Windows 2000 only)
Find the first available media, format it, and use for the current backup.
Use with the /p switch to scan for available media pools.
This command is only for standalone tape devices (not tape loaders.)
The /UM switch must be at the end of the command line.
NSLOOKUP (TCP/IP)
Lookup IP addresses on a NameServer.
Syntax
Lookup the ip address of MyHost:
NSLOOKUP [-option] MyHost
Lookup ip address of MyHost on MyNameServer:
NSLOOKUP [-option] MyHost MyNameServer
Enter “command mode”:
NSLOOKUP
Command Mode options:
help or ? - print a list of Command Mode options
exit or ^C - exit “command mode”
set all - print options, current server and host
finger [USER] - finger the optional NAME at the current default host
MyHost - print ip address of MyHost
MyHost MyNameServer - print ip address of MyHost on MyNameServer
set [no]debug - print debugging info
set [no]d2 - print exhaustive debugging info
set domain=NAME - set default domain name to NAME
set root=NAME - set root server to NAME
root - set current default server to the root
server NAME - set default server to NAME, using current default server
lserver NAME - set default server to NAME, using initial server
set srchlist=N1[/N2/…/N6] - set domain to N1 and search list to N1, N2,…
set retry=X - set number of retries to X
set timeout=X - set initial time-out interval to X seconds
set [no]defname - append domain name to each query
set [no]recurse - ask for recursive answer to query
set [no]search - use domain search list
set [no]vc - always use a virtual circuit
set class=X - set query class (for example, IN (Internet), ANY)
set [no]msxfr - use MS fast zone transfer
set ixfrver=X - current version to use in IXFR transfer request
set type=X - set query type
set querytype=X - set query type
(e.g. A, ANY, CNAME, MX, NS, PTR, SOA, SRV)
ls [opt] DOMAIN [> FILE] - list addresses in DOMAIN
(and optionally output to FILE)
-d - list all records
-t TYPE - list records of the given Type (for example, A, CNAME,
MX, NS, PTR, and so on)
-a - list Aliases and canonical names.
view FILE - sort an ‘ls’ output file and view it with pg
Example:
C:\> nslookup -querytype=TXT -timeout=10 porttest.dns-oarc.net
Below are the Privileges that can be granted or revoked, all are Case-
Sensitive.
Logon Privileges:
Log on as a batch job SeBatchLogonRight
Deny logon as a batch job SeDenyBatchLogonRight
Log on locally SeInteractiveLogonRight
Deny local logon SeDenyInteractiveLogonRight
Logon as a service SeServiceLogonRight
Deny logon as a service SeDenyServiceLogonRight
Access this Computer from the Network SeNetworkLogonRight
Deny Access to this computer from the network SeDenyNetworkLogonRight
Allow logon through Terminal Services SeRemoteInteractiveLogonRight (Not supported on
Win 2000)
Deny logon through Terminal Services SeDenyRemoteInteractiveLogonRight (Not supported on
Win 2000)
Service Privileges:
Create permanent shared objects SeCreatePermanentPrivilege
Create a token object SeCreateTokenPrivilege
Replace a process-level token SeAssignPrimaryTokenPrivilege
Impersonate a client after authentication SeImpersonatePrivilege (Not supported on 21st Century
Windows Releases or earlier)
Increase scheduling priority SeIncreaseBasePriorityPrivilege
Act as part of the operating system SeTcbPrivilege
Profile a single process SeProfileSingleProcessPrivilege
Load and unload device drivers SeLoadDriverPrivilege
Lock pages in memory SeLockMemoryPrivilege
Create global objects SeCreateGlobalPrivilege (Not supported on Windows XP or earlier)
Misc Privileges:
Debug programs SeDebugPrivilege
Bypass traverse checking SeChangeNotifyPrivilege
Synch directory service data SeSyncAgentPrivilege
Edit firmware environment values SeSystemEnvironmentPrivilege
Profile system performance SeSystemProfilePrivilege
Obsolete and unused SeUnsolicitedInputPrivilege (has no effect)
OPENFILES.exe
Query or display open files, disconnect files opened by network users.
Syntax
Openfiles.exe /query [/s Computer [/u Domain\User [/p Password]]]
[/fo {TABLE|LIST|CSV}] [/nh] [/v]
Openfiles.exe /disconnect [/s Computer [/u Domain\User [/p Password]]]
{[/id OpenFileID]|[/a UserName]|[/o OpenMode]} [/se SessionName] [/op OpenFileName]
Key
/s The name or IP address of a remote computer. (Do not use backslashes.) default=local computer.
/u Run the command with the account permissions of user. Default=current logged on user.
/p The password of the user account specified with /u.
/fo The format to use for the query output. Valid values are TABLE, LIST, and CSV.
Default=TABLE.
/nh No column headers in the output. Valid only when /fo = TABLE or CSV.
/id Disconnect the file opened with the specified numeric OpenFileID on computer
Use openfiles.exe /query to learn the file ID.
The wildcard (*) can be used to disconnect all open files on computer.
/a Disconnect all open files that were accessed by user on computer.
The wildcard (*) can be used to disconnect all open files on computer.
/o Disconnect all open files with the specified OpenMode on the computer specified by the /s
parameter.
The OpenMode parameter includes the Read/Write and Read modes.
The wildcard (*) can be used to disconnect all open files on computer.
/se Disconnect all open files that were created by the specified session on computer.
Wildcards (*) may be used. (the /se option is not available under Windows 7)
/op Disconnect the open file that was created with the specified OpenFileName on computer
The wildcard (*) can be used to disconnect all open files on computer.
/v Display verbose information in the output.
/? Help.
PAUSE
Pause the execution of a batch file
Syntax
PAUSE
TypePerf.exe
Write performance data to the command window or to a log file.To stop
Typeperf, press CTRL+C.
Syntax
typeperf counter [counter …] [options]
typeperf -cf filename [options]
typeperf -q [object] [options]
typeperf -qx [object] [options]
Key
counter The Performance counters to monitor.
-f {CSV|TSV|BIN|SQL} Output file format. Default is CSV.
-cf filename File containing performance counters to monitor, one per line.
-si [[hh:]mm:]ss Time between samples. Default is 1 second.
-o filename Path of output file or SQL database.
Default is STDOUT.
-q [object] List installed counters (no instances).
To list counters for one object,
include the object name, such as Processor.
-qx [object] List installed counters with instances.
To list counters for one object,
include the object name, such as Processor.
-sc samples Number of samples to collect. Default is
to sample until CTRL+C.
-config filename Settings file containing command options.
-s computer_name Server to monitor if no server is specified in the counter path.
-y Answer yes to all questions without prompting.
-? Display context sensitive help.
PING
Test a network connection - if successful, ping returns the ip address.
Syntax
PING [options] destination_host
Options
-w timeout Timeout in milliseconds to wait for each reply.
-i TTL Time To Live.
-v TOS Type Of Service.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-t Ping the destination host until interrupted.
To see statistics and continue type Control-Break;
To stop type Control-C.
-l size Send buffer size.
-f Set Don’t Fragment flag in packet (IPv4-only).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host_list Loose source route along host_list (IPv4-only).
-k host_list Strict source route along host_list (IPv4-only).
destination_host The name of the remote host
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
A response of “Request timed out” means there was no response to the
ping attempt in the default time period of one second.
If the latency of the response is more than one second. Use the -w option on
the ping command to increase the time-out. For example, to allow responses
within five seconds, use ping -w 5000.
The IPv6 options are only available on versions of Windows that support
IPv6, e.g. Windows 7 /2008
A successful PING does NOT always return an %errorlevel% == 0
Therefore to reliably detect a successful ping - pipe the output into FIND and
look for the text “TTL”
Note that “Reply” in the output of PING does not always indicate a positive
response. You may receive a message from a router such as: Reply from
192.168.1.254: Destination Net Unreachable.
Four steps to test an IP connection with ping:
1) Ping the loopback address to verify that TCP/IP is installed and configured
correctly on the local computer.
PING 127.0.0.1
2) Ping the IP address of the local computer to verify that it was added to the
network correctly.
PING IP_address_of_local_host
3) Ping the IP address of the default gateway to verify that the default
gateway is functioning and that you can communicate with a local host on the
local network.
PING IP_address_of_default_gateway
4) Ping the IP address of a remote host to verify that you can communicate
through a router.
PING IP_address_of_remote_host
Examples
Ping a server just once:
PING -n 1 Server64
The script above can be used to test an Internet connection, just replace
example.com with your ISP’s Default Gateway IP address. This represents
the first physical device on the ISP’s side of your connection. You can find
the Default Gateway on your router status screen.
Note: some ISP’s or network admins may not appreciate you performing
frequent or continual pings to their server, try not to overdo it!
PING is named after the sound that a sonar makes.
Ping response times below 10 milliseconds often have low accuracy. A
time of 10 milliseconds is roughly equal to a distance of 930 Miles, travelling
a straight line route at the speed of light.
POPD
Change directory back to the path/folder most recently stored by the
PUSHD command.
POPD will also remove any temporary drive maps created by PUSHD
Syntax
POPD
Example
c:\Program Files> PUSHD c:\utils
c:\utils> PUSHD c:\WINNT
c:\Winnt>
c:\Winnt> POPD
c:\utils>
c:\utils> POPD
c:\Program Files>
If Command Extensions are disabled PUSHD and POPD will not create
temporary drive letters.
PowerCFG (Vista/Windows7/Server
2008)
Control power settings, configure Hibernate/Standby modes. See also the
Windows XP SP2 version of PowerCfg.
Syntax
powercfg [Options]
Options
-l
-list
List the current user’s power schemes (GUIDs)
-query [Scheme_GUID] [Sub_GUID]
-q [Scheme_GUID] [Sub_GUID]
Display the contents of a power scheme.
-change settingvalue
-x setting value
Modify one of the following settings in the current power scheme:
-monitor-timeout-ac minutes
-monitor-timeout-dc minutes
-disk-timeout-ac minutes
-disk-timeout-dc minutes
-standby-timeout-ac minutes
-standby-timeout-dc minutes
-hibernate-timeout-ac minutes
-hibernate-timeout-dc minutes
Setting any value to 0 will set the timeout=Never
AC settings are used when the system is on AC power. DC settings on battery power.
-changename GUID PowerSchemeName [scheme_description]
Modify the name of a power scheme and, optionally, the scheme description.
-duplicatescheme GUID [DestinationGUID]
Duplicate a power scheme. The GUID of the new scheme will be displayed.
If DestinationGUID is omitted, then a new GUID will be created for the duplicated scheme.
-delete GUID
-d GUID
Delete the power scheme with the specified GUID.
-deletesetting Sub_GUID Setting_GUID
Delete a power setting.
-setactive Scheme_GUID
-s Scheme_GUID
Make the specified power scheme active on the computer.
-getactivescheme
Retrieve the currently active power scheme.
-setacvalueindex Scheme_GUID Sub_GUID Setting_GUID SettingIndex
Set a value associated with a specified power setting while the
computer is powered by AC power. Use the -l and -q options to discover the GUIDs
SettingIndex Specifies which value in the list to set, so 3 = 3rd in the list
-setdcvalueindex Scheme_GUID Sub_GUID Setting_GUID SettingIndex
Set a value associated with a specified power setting while the
computer is powered by DC power.
SettingIndex Specifies which value in the list to set, so 3 = 3rd in the list
-hibernate [on|off]
-h [on|off]
Enable or disable the hibernate feature. Hibernate timeout is not supported on all computers.
-availablesleepstates
-a
Report the sleep states available on the computer.
Will also attempt to report reasons why sleep states are unavailable.
-devicequery query_flags
Return a list of devices that meet the specified flags:
wake_from_S1_supported – Waking the computer from a light sleep state.
wake_from_S2_supported – Waking the computer from a deeper sleep state.
wake_from_S3_supported – Waking the computer from the deepest sleep state.
wake_from_any – Support waking the computer from any sleep state.
S1_supported – Light sleep.
S2_supported – Deeper sleep.
S3_supported – Deepest sleep.
S4_supported – Hibernation.
wake_programmable – User-configurable to wake the computer from a sleep state.
wake_armed – Currently configured to wake the computer from any sleep state.
all_devices – Present in the computer.
all_devices_verbose – Verbose list of devices.
-deviceEnableWake devicename
Enable the device to wake the computer from a sleep state.
-deviceDisableWake devicename
Disable the device from waking the computer from a sleep state.
-import filename [GUID]
Import all power settings from the specified file.
filename is the path to a file generated with powercfg -export
-export filename GUID
Export a power scheme, represented by GUID, into filename.
-lastwake
Report information about the last event that woke the computer.
-energy
Create energy-report.html in the current directory, Windows7 only.
-help
-?
Display help
-aliases
Display all aliases and their corresponding GUIDs.
These may be used in place of a GUID at the command prompt
-setsecruitydescriptor [GUID|Action] SDDL
Set a security descriptor associated with a specified power setting, power scheme, or action.
Action Is one of: ActionSetActive, ActionCreate, ActionDefault
SDDL is a valid security descriptor string in SDD format.
Call powercfg -getsecuritydescriptor to see an example SDDL STRING.
-getsecuritydescriptor [GUID|Action]
Get a security descriptor associated with a specified power setting, power scheme, or action.
Action is one of: ActionSetActive, ActionCreate, ActionDefault
Set the Monitor and disc timeouts for the current Power saver scheme
C:\> Powercfg -Change -monitor-timeout-ac 20
C:\> Powercfg -Change -disk-timeout-ac 30
Enable the mouse to wake from sleep
C:\> Powercfg -deviceEnableWake “Microsoft USB IntelliMouse Explorer”
PRINT
Print a file or files to a local or network printer.
Syntax
PRINT [/D:device] [pathname(s)]
Key
device : either a local printer (LPTx, COMx )
or a network printer by its sharename (\servername\print_share)
pathname : The file or files to be printed
The default device is PRN. The values PRN and LPT1 refer to the same
parallel port.
PRINTBRM.exe
Print queue Backup/Recovery/Migration.
Syntax
PRINTBRM -b -s \server_name -f file_name options
PRINTBRM -r -s \server_name -f file_name options
PRINTBRM -q options
Key
-s server_name The unc path to the print server.
-b Back up the server to the specified file.
-r Restore the configuration in the file to the server.
-q Query the server or the backup file.
-f file_name The backup file.
-d directory Unpack the backup file to the directory (with -r),
or repack a backup file from the directory (with -b).
-o force Forces overwriting of existing objects.
-p all Publish all printers in the directory, or
-p org Publish the printers that were originally published.
-nobin Omit binary files from the backup.
-lpr2tcp Convert LPR ports to standard TCP/IP ports on restore.
-c file_name Use the specified configuration file.
-noacl Remove ACLs from print queues on restore.
In Windows 2008 PrintBRM replaces the old Win 2003 PrintMig utility,
it is backwards compatible with 2003.
Get a list of all printer share names for a print server: net view
\printserv1
Examples
prnmngr -a -p “printer” -m “driver” -r “lpt1:”
prnmngr -d -p “printer” -s server
prnmngr -ac -p “\server\printer”
prnmngr -d -p “\server\printer”
prnmngr -x -s server
prnmngr -l -s server
prnmngr -l |find “Printer name”
prnmngr -g
prnmngr -t -p “\server\printer”
PROMPT
Change the cmd.exe command prompt.
Syntax
PROMPT [text]
Key
text : a text string.
The prompt text can be made up of normal characters and the following
special codes:
$A & (Ampersand)
$B | (pipe)
$C ( (Left parenthesis)
$D Current date
$E Escape code (ASCII code 27)
$F ) (Right parenthesis)
$G > (greater-than sign)
$H Backspace (erases previous character)
$L < (less-than sign)
$M Display the remote name for Network drives
$N Current drive
$P Current drive and path
$Q = (equal sign)
$S (space)
$T Current time
$V Windows NT version number
$_ Carriage return and linefeed
$$ $ (dollar sign)
$+ Will display plus signs (+) one for each level of the PUSHD directory stack
Examples
Display the UNC path whenever you are using a network drive (mapped with NET USE)
PROMPT $M$_$P$G
Simulate an HP-UX style prompt with the computername and the current folder on separate lines:
PROMPT=$p$_%username%@%computername%:.
Restore the default prompt:
PROMPT $P$G
You can also create a shortcut to the command prompt like this:
CMD /K PROMPT $M$_$P$G
* In fact the prompt variable is a property of the CMD console, it’s not
available to Windows Explorer or any other applications, so strictly speaking
is not an environment variable.
If Command Extensions are disabled the commands $M and $+ are not
supported.
Psexec can also be used to start GUI applications, but in that case the
GUI will appear on the remote machine.
Input is passed to the remote system when you press the enter key -
typing Ctrl-C will terminate the remote process.
When you specify a username the remote process will execute in that
account, and will have access to that account’s network resources.
If you omit username the remote process will run in the same account
from which you execute PsExec, but because the remote process is
impersonating it will not have access to network resources on the remote
system.
If you do specify an alternative username/password, then PsExec will
send the password in clear text. This may be a security risk if unauthorized
network sniffers could intercept traffic between the local and remote system.
PsExec does not require you to be an administrator of the local
filesystem this can allow UserA to run commands as UserB - a Runas
replacement.
Surround any long filenames “with quotation marks”
Examples:
Unlike the NET FILE command, PsFile does not truncate long
filenames.
Examples:
List all the files on \workstation64 that have been opened remotely:
psfile \workstation64
PATHPING
Trace route and provide network latency and packet loss for each router
and link in the path. Combines the functionality of PING and TRACERT.
Syntax
PATHPING [-n] [-h max_hops] [-g host_list] [-p period]
[-q num_queries] [-w timeout] [-i IPAddress] [-4 ] [-6 ][TargetName]
Key
-g host_list - Loose source route along host-list.
-h max_hops - Maximum number of hops to search for target.
-i address - Use the specified source address.
-n - Do not resolve addresses to hostnames.
-p period - Wait period milliseconds between pings.
-q num_queries - Number of queries per hop.
-w timeout - Wait timeout milliseconds for each reply.
-P - Test for RSVP PATH connectivity.
-R - Test if each hop is RSVP aware.
-T - Test connectivity to each hop with Layer-2 priority tags.
-4 - Force using IPv4.
-6 - Force using IPv6.
RECOVER
Recover a damaged file from a defective disk.
Syntax
RECOVER [drive:][path]filename
The data on a disk is stored in tracks and sectors in an almost random manner.
Data stored in a bad sectors cannot be read.
RECOVER reads a file sector by sector and recovers data from the good
sectors. You must specify a filename.
REG.exe
Read, Set or Delete registry keys and values, save and restore from a
.REG file.
Syntax:
REG QUERY [ROOT\]RegKey /v ValueName [/s]
REG QUERY [ROOT\]RegKey /ve —This returns the (default) value
REG ADD [ROOT\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f]
REG ADD [ROOT\]RegKey /ve [/d Data] [/f] — Set the (default) value
REG DELETE [ROOT\]RegKey /v ValueName [/f]
REG DELETE [ROOT\]RegKey /ve [/f] — Remove the (default) value
REG DELETE [ROOT\]RegKey /va [/f] — Delete all values under this key
REG COPY [\SourceMachine\][ROOT\]RegKey [\DestMachine\][ROOT\]RegKey
REG EXPORT [ROOT\]RegKey FileName.reg
REG IMPORT FileName.reg
REG SAVE [ROOT\]RegKey FileName.hiv
REG RESTORE \MachineName\[ROOT]\KeyName FileName.hiv
REG LOAD FileName KeyName
REG UNLOAD KeyName
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/v ValueName] [Output] [/s]
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/ve] [Output] [/s]
Key:
ROOT :
HKLM = HKey_Local_machine (default)
HKCU = HKey_current_user
HKU = HKey_users
HKCR = HKey_classes_root
ValueName : The value, under the selected RegKey, to edit.
(default is all keys and values)
/d Data : The actual data to store as a “String”, integer etc
/f : Force an update without prompting “Value exists, overwrite Y/N”
\Machine : Name of remote machine - omitting defaults to current machine.
Notes:
Any of the above commands can be run against a remote machine by adding
\MachineName to the command line, assuming the Remote Registry Service
is running.
Registry data stored under HKCU will be visible and writable by the currently
logged in user.
Registry data stored under HKLM will be visible to all users and writable by
administrators.
To include a quote mark (“) in the data, prefix it with the escape character (\)
e.g. “Here is \” a quote”
Enclose ValueNames that contain the \ character in single quotes.
REG RESTORE has a tendency not to work, possibly due to firewall issues,
Export and Import are much more reliable.
Examples
REG QUERY HKCU\Console\
REG QUERY HKCU\Console /v ScreenBufferSize
Find the location of the Start Menu folder:
REG QUERY “HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell
Folders” /v “Start Menu”
REG ADD HKCU\Software\EXAMPLE /v Sample /d “some test data”
REG QUERY HKCU\Software\EXAMPLE /v Sample
REG ADD HKLM\Software\DiLithium /v WarpSpeed /t REG_BINARY /d ffffffff
REG QUERY HKLM\Software\DiLithium /v WarpSpeed
REG COPY \Wks580\HKCU\Software\EXAMPLE HKCU\Software\EXAMPLE
REG COPY HKCU\Software\EXAMPLE HKCU\Software\EXAMPLECopy
REG EXPORT HKCU\Software\EXAMPLE C:\MyReg.REG
REG IMPORT C:\MyReg.REG
REG SAVE HKCU\Software\EXAMPLE C:\MyRegHive.hiv
REG RESTORE \Wks580\HKCU\Software\EXAMPLE C:\MyRegHive.hiv
Run a script at first logon (Run Once) to do this we edit the Default User
profile by temporarily loading it as ZZZ:
REG LOAD HKU\ZZZ “C:\Documents and Settings\Default User\NTUSER.DAT”
REG ADD HKU\ZZZ\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce /v
newUserProfile /t REG_EXPAND_SZ /d “D:\setup.cmd” /f
REG UNLOAD HKU\ZZZ
More examples are available via: REG QUERY /? REG ADD /? etc
REGEDIT
Import, export or delete registry settings from a text (.REG) file
Syntax
Export the Registry (all HKLM plus current user)
REGEDIT /E pathname
Export part of the Registry
REGEDIT /E pathname “RegPath”
Import a reg script
REGEDIT pathname
Silent import
REGEDIT /S pathname
Start the regedit GUI
REGEDIT
Open multiple copies of GUI (XP and 2003 only)
REGEDIT -m
Key
/E : Export
/S : Silent Import
When double clicking this .reg file the key and value will be added.
Alternatively run REGEDIT MYKEY.REG from the command line.
How to delete keys and values from the registry:
Create a reg file like this, notice the hyphen inside the first bracket
Windows Registry Editor Version 5.00
[-HKEY_CURRENT_USER\SomeKey]
When double clicking this .reg file the key “SomeKey” will be deleted
along with all string, binary or Dword values in that key.
If you want to just delete values, leaving the key in place, set the value you
want to delete = to a hyphen
e.g.
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SomeKey]
“SomeStringValue”=-
Again double clicking this .reg file will delete the values specified, or
you can use REGEDIT /s MyDeleteScript.REG
Comments
Within a registry file, comments can be preceded by “; ”
e.g.
;
; Turn the NUMLOCK on at login
;
[HKEY_CURRENT_USER\Control Panel\Keyboard]
“InitialKeyboardIndicators”=“2”
Under Windows NT 4 all registry scripts start with: REGEDIT4
(This version string will also work in XP and later versions of Windows.)
REGSVR32
Register or unregister a DLL.
Syntax
REGSVR32 [/U] [/S] [/C] [/I:[Command_Line]] DLL_Name
REGSVR32 [/U] [/S] [/C] /N /I:[Command_Line] DLL_Name
Key
/u Unregister Server.
/s Silent - no dialogue boxes.
/c Console output.
/n Don’t call DllRegisterServer
/i Call DllInstall (or DllUninstall if /u is specified)
Command_Line An optional command line for DllInstall
Examples
Unregister (disable) XP Zip folders
REGSVR32 /u C:\Windows\System32\zipfldr.dll
Unregister (Disable) CAB file viewer:
REGSVR32 /u C:\Windows\System32\cabview.dll
Register (enable) XP Zip folders
REGSVR32 zipfldr.dll
Register (enable) CAB file viewer:
REGSVR32 cabview.dll
Register Windows Update DLLs (for those times when XP repair breaks
Windows Update)
regsvr32 /s wuapi.dll
regsvr32 /s wuaueng1.dll
regsvr32 /s wuaueng.dll
regsvr32 /s wucltui.dll
regsvr32 /s wups2.dll
regsvr32 /s wups.dll
regsvr32 /s wuweb.dll
Register DAO 3.6 (Data Access Objects):
REGINI (*)
Change Registry Permissions.
Syntax
REGINI [-m \machinename | -h hivefile hiveroot | -w Win95Directory]
[-i n] [-o outputWidth]
[-b] textFiles…
Key
-m A remote computer.
-h The local hive to manipulate.
-w Path to Windows 95 system.dat / user.dat files
-i n The display indentation multiple. Default is 4
-o outputWidth
How wide the output is to be. By default the
outputWidth is set to the width of the console window if standard
output has not been redirected to a file. In the latter case, an
outputWidth of 240 is used.
-b Make REGINI backward compatible with older versions of REGINI that
did not strictly enforce line continuations and quoted strings
Specifically, REG_BINARY, REG_RESOURCE_LIST and
REG_RESOURCE_REQUIREMENTS_LIST data types did not need line
continuations after the first number that gave the size of the data.
It just kept looking on following lines until it found enough data
values to equal the data length or hit invalid input. Quoted
strings were only allowed in REG_MULTI_SZ. They could not be
specified around key or value names, or around values for REG_SZ or
REG_EXPAND_SZ Finally, the old REGINI did not support the semicolon
as an end of line comment character.
textFiles One or more ANSI or Unicode text files with registry data.
The easiest way to understand the format of the input textFile is to use
the REGDMP command with no arguments to dump the current contents of
your NT Registry to standard out. Redirect standard out to a file and this file
is acceptable as input to REGINI
Values should come before child keys, as they are associated with the
previous key at or above the value’s indentation level.
For key names, leading and trailing space characters are ignored and not
included in the key name, unless the key name is surrounded by quotes.
Imbedded spaces are part of a key name.
If there is an equal sign on the same line as a left square bracket then the
equal sign takes precedence, and the line is treated as a registry value. If the
text between the square brackets is the string DELETE with no spaces, then
REGINI will delete the key and any values and keys under it.
For registry values, the syntax is:
value Name = type data
Leading spaces, spaces on either side of the equal sign and spaces
between the type keyword and data are ignored, unless the value name
is surrounded by quotes. If the text to the right of the equal sign is the string
DELETE, then REGINI will delete the value.
The value name may be left off or be specified by an at-sign character which
is the same thing, namely the empty value name. So the following two lines
are identical:
= type data
@ = type data
This syntax means that you can’t create a value with leading or trailing
spaces, an equal sign or an at-sign in the value name, unless you put the name
in quotes.
Valid value types and format of data that follows are:
REG_SZ text
REG_EXPAND_SZ text
REG_MULTI_SZ “string1” “str””ing2” …
REG_DATE mm/dd/yyyy HH:MM DayOfWeek
REG_DWORD numberDWORD
REG_BINARY numberOfBytes numberDWORD(s)…
REG_NONE (same format as REG_BINARY)
REG_RESOURCE_LIST (same format as REG_BINARY)
REG_RESOURCE_REQUIREMENTS (same format as REG_BINARY)
REG_RESOURCE_REQUIREMENTS_LIST (same format as REG_BINARY)
REG_FULL_RESOURCE_DESCRIPTOR (same format as REG_BINARY)
REG_QWORD numberQWORD
REG_MULTISZ_FILE fileName
REG_BINARYFILE fileName
If no value type is specified, default is REG_SZ
For REG_BINARY, the value data consists of one or more numbers The
default base for numbers is decimal. Hexidecimal may be specified by using
0x prefix. The first number is the number of data bytes, excluding the first
number. After the first number must come enough numbers to fill the value.
Each number represents one DWORD or 4 bytes. So if the first number was
0x5 you would need two more numbers after that to fill the 5 bytes. The high
order 3 bytes
of the second DWORD would be ignored.
There are several versions of regini with different syntax - the resource
kit includes a word document with help and examples.
REM
In a batch file REM at the start of a line signifies a comment or
REMARK
alternatively adding :: at the start of a line has a similar effect
For example:
@ECHO OFF
::
:: First comment
::
REM Second comment
REM
::
Although you can use rem without a comment to add vertical spacing to a
batch file, you can also use completely blank lines. The blank lines are
ignored when processing the batch program.
The double-colon is not documented as a comment command, it is a
special case of a CALL label that acts like a comment. The pro’s and cons of
each method are listed below.
Bugs
There are problems using a :: comment within an IF or FOR code bracket
e.g.
@echo off
FOR /L %%i IN (1,1,10) Do (
Echo before comment
:: Some comment
Echo after comment
)
The above will return the error :: was unexpected at this time.
In Windows 2000 and XP a comment like
::%~
or
REM %~ will be interpreted giving the error:
The following usage of the path operator in batch-parameter substitution is
invalid: %~
In Windows NT 4 the REM command would incorrectly reset the
%errorlevel% to 0
The bottom line on this is that you must test your comments to be sure
they will be ignored as you expect.
Registry Comments
Within a registry file comments can be preceded by “; ”
e.g.
;
; Turn the NUMLOCK on at login
;
[HKEY_CURRENT_USER\Control Panel\Keyboard]
“InitialKeyboardIndicators”=“2”
FTP Comments
There is no valid comment character for FTP but you can cheat by
escaping to the shell and running REM
e.g.
C:\WORK>type ftpscript
!REM This is a remark
bye
C:\WORK>ftp -s:ftpscript
ftp> !REM This is a remark
ftp> bye
C:\WORK>
REN
Rename a file or files.
REN [drive:][path]old_filename new_filename
You cannot specify a different drive or path for `new_filename` - use the
MOVE command instead.
REPLACE
Replace or update one file with another
Syntax
REPLACE Source_PathName Destination_path [/A] [/P] [/R] [/W]
REPLACE Source_PathName Destination_path [/P] [/R] [/S] [/W] [/U]
Key
path : The folder where files are to be replaced.
/A : Add any missing files.
/P : Prompt for confirmation (each file)
/R : Replace even Read-only files
/S : Include all subfolders of the destination.
/W : Wait for you to insert a floppy disk.
/U : Replace (update) only files that are older than the source.
Limitations:
When replacing in all subdirectories (/S ) you cannot ADD files (/A) or
restrict to replacing older files (/U)
RD
Delete folder(s)
Syntax
RD pathname
RD /S pathname
RD /S /Q pathname
Key
/S : Delete all files and subfolders
in addition to the folder itself.
Use this to remove an entire folder tree.
/Q : Quiet - do not display YN confirmation
Place any long pathnames in double quotes.
RD does not support wildcards but you can remove several folders in one
command by listing the pathname to each.
e.g.
Move files over 14 days old: (note the MOVE option will fail if any files
are open and locked.)
ROBOCOPY C:\work C:\destination /move /minage:14
Backup a Server
The script below copies data from FileServ1 to FileServ2, the destination
holds a full mirror along with file security info. When run regularly to
synchronize the source and destination, robocopy will only copy those files
that have changed (change in time stamp or size.)
@ECHO OFF
SETLOCAL
SET _source=\FileServ1\e$\users
SET _dest=\FileServ2\e$\BackupUsers
SET _what=/COPYALL /B /SEC /MIR
:: /COPYALL :: COPY ALL file info
:: /B :: copy files in Backup mode.
:: /SEC :: copy files with SECurity
:: /MIR :: MIRror a directory tree
Bugs
Version XP026 returns a success errorlevel even when it fails.
## = New Option in Vista (XP027) all other options on this page are for
the XP version of Robocopy (XP010)
### = New Option in Windows 7 and Windows 2008 R2
Robocopy EXIT CODES
File Attributes [RASHCNETO]
R – Read only
A – Archive
S – System
H – Hidden
C – Compressed
N – Not content indexed
E – Encrypted
T – Temporary
O - Offline
Move files over 14 days old: (note the MOVE option will fail if any files
are open and locked.)
ROBOCOPY C:\work C:\destination /move /minage:14
Backup a Server
The script below copies data from FileServ1 to FileServ2, the destination
holds a full mirror along with file security info. When run regularly to
synchronize the source and destination, robocopy will only copy those files
that have changed (change in time stamp or size.)
@ECHO OFF
SETLOCAL
SET _source=\FileServ1\e$\users
SET _dest=\FileServ2\e$\BackupUsers
SET _what=/COPYALL /B /SEC /MIR
:: /COPYALL :: COPY ALL file info
:: /B :: copy files in Backup mode.
:: /SEC :: copy files with SECurity
:: /MIR :: MIRror a directory tree
Bugs
Version XP026 returns a success errorlevel even when it fails.
ROUTE.exe
Manipulate network routing tables. Route packets of network traffic
from one subnet to another by modifying the route table.
Syntax
Display route details:
ROUTE [-f] PRINT [destination_host] [MASK subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Add a route:
ROUTE [-f] [-p] ADD [destination_host] [MASK subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Change a route:
ROUTE [-f] CHANGE [destination_host] [MASK subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Delete a route:
ROUTE [-f] DELETE [destination_host] [MASK subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
key
-f Clear (flush) the routing tables of all gateway entries. If this is
used in conjunction with one of the commands, the tables are
cleared prior to running the command.
destination_host
The address (or set of addresses) that you want to reach.
-p Create a persistent route - survives system reboots.
(not supported in Windows 95)
subnet_mask_value
The subnet mask value for this route entry.
This defines how many addresses are there.
If not specified, it defaults to 255.255.255.255.
gateway The gateway.
interface The interface number (1,2,…) for the specified route.
If the option `IF interface_no` is not given, ROUTE will try
to find the best interface available.
metric The metric, ie. cost for the destination.
Note that routes added to the table are not made persistent unless the -p
switch is specified. Non-persistent routes only last until the computer is
rebooted.
Symbolic names used for Destination_Host are looked up in the network
database file NETWORKS.
The symbolic names for gateway are looked up in the host name database file
HOSTS.
RUNAS
Execute a program under a different user account.
Syntax
RUNAS [/profile] [/env] [/netonly] /user:user Program
Key
/profile Option to load the user’s profile (registry)
/env Use current environment instead of user’s.
/netonly Use the credentials specified only for remote connections.
/user Username in form USER@DOMAIN or DOMAIN\USER
(USER@DOMAIN is not compatible with /netonly)
Program The command to execute
Run Notepad.exe and open a file, escape the quote characters around the
filename with \
Runas /env /user:jDoe@swest.example.com “NOTEPAD \“my file.txt\””
Notes:
The backslash \ is NOT the standard escape character used by other CMD
commands.
RunAs Reqires the “Secondary Logon” service to be running.
RunDLL32.exe
Run a DLL program. This command is available on all version of
Windows from Win95 onwards, but the DLL’s and options available do vary
considerably. Many options are case sensitive.
Syntax
RUNDLL32.EXE dll_name,EntryPoint [options]
Examples
Un-install MS Java Virtual Machine (JVM):
RUNDLL32 advpack.dll,LaunchINFSection java.inf,UnInstall
Copy a floppy disk
RUNDLL32 diskcopy,DiskCopyRunDll
Lock workstation
RUNDLL32.exe user32.dll, LockWorkStation
Add a Network Printer
RUNDLL32 printui.dll,PrintUIEntry /ia /c\server /m “AGFA-AccuSet v52.3”
/h “Intel” /v “Windows 2000” /f %windir%\inf\ntprint.inf
Add a Local Printer
RUNDLL32 printui.dll,PrintUIEntry /if /b “Test Printer” /c\SERVER
/f “%windir%\inf\ntprint.inf” /r “lpt1:” /m “AGFA-AccuSet v52.3”
Add a printer connection that’s available to anyone who logs on:
Rundll32 printui.dll,PrintUIEntry /ga /n\Server\PrintShare
Display all the available commands for PRINTUI.DLL
RUNDLL32 printui.dll,PrintUIEntry /?
(add/remove print drivers, print queues, preferences, properties etc)
SC.exe (*)
Service Control - Create, Start, Stop, Query or Delete any Windows
SERVICE. The command options for SC are case sensitive.
Syntax
SC [\server] [command] [service_name] [Options]
Key
server : The machine where the service is running
service_name : The KeyName of the service, this is often but not always
the same as the DisplayName shown in Control Panel, Services.
You can get the KeyName by running:
SC GetKeyName <DisplayName>
commands:
query [qryOpt] Show status
queryEx [qryOpt] Show extended info - pid, flags
GetDisplayName Show the DisplayName
GetKeyName Show the ServiceKeyName
EnumDepend Show Dependencies
qc Show config - dependencies, full path etc
start START a service.
stop STOP a service
pause PAUSE a service.
continue CONTINUE a service.
create Create a service. (add it to the registry)
config permanently change the service configuration
delete Delete a service (from the registry)
control Send a control to a service
interrogate Send an INTERROGATE control request to a service
Qdescription Query the description of a service
description Change the description of a service
Qfailure Query the actions taken by a service upon failure
failure Change the actions taken by a service upon failure
sdShow Display a service’s security descriptor using SDDL
SdSet Sets a service’s security descriptor using SDDL
qryOpt:
type= driver|service|all
Query specific types of service
state= active|inactive|all
Query services in a particular state only
bufsize= bytes
ri= resume_index_number (default=0)
group= groupname
Query services in a particular group
Misc commands that don’t require a service name:
SC QueryLock Query the LockStatus for the ServiceManager Database.
this will show if a service request is running
SC Lock Lock the Service Database
SC BOOT Values are {ok | bad} Indicates whether to save
the last restart configuration as the `last-known-good`
restart configuration
Options
The CREATE and CONFIG commands allow additional options to be set
see the build-in help: ‘SC create’ and ‘SC config’
Note the qryOpt options above are case sensitive - they must be entered
in lower case, also the position of spaces and = must be exactly as shown.
The SC command duplicates some aspects of the NET command but
adds the ability to create a service.
SC query will display if a service is running, giving output like this:
SERVICE_NAME : messenger
TYPE : 20 WIN32_SHARE_PROCESS
STATE : 4 RUNNING
(STOPPABLE,NOT_PAUSABLE,ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
The NET START command can be used in a similar way to check if a service
is running:
NET START | FIND “Service name” > nul
IF errorlevel 1 ECHO The service is not running
SCHTASKS
Create, delete, edit, list, start or stop a scheduled task.
Works on local or remote computers.
Syntax:
SCHTASKS /Create [Connect_Options] Create_Options /TN taskname
SCHTASKS /Delete [Connect_Options] /TN taskname [/F]
SCHTASKS /Query [Connect_Options] [/FO format] [/NH] [/V]
SCHTASKS /Run [Connect_Options] /TN taskname
SCHTASKS /End [Connect_Options] /TN taskname
SCHTASKS /Change [Connect_Options] {[/RU username] [/RP password] [/TR taskrun]} /TN
taskname
Connect_Options:
/S system # Remote system (default is local)
[/U username [/P password]] # Submit job under this name
Create_Options:
/TR taskrun # Pathname of the executable to run
/ST starttime # HH:MM:SS (24 hour)
[/RU username [/RP password]] # Run job as this user
/SC schedule [/MO modifier] # When to run, see below
[/D day] # Day = MON,TUE,WED,THU,FRI,SAT,SUN
[/M months] # Month=JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC.
[/I idletime] # 1 - 999 minutes (ONIDLE task only)
[/SD startdate] [/ED enddate] # Start and end date “dd/mm/yyyy”
options:
/TN A name for the task
/F Force delete, ignore warnings even if the task is currently runnning.
/FO Output format: TABLE, LIST, CSV
/NH No header
/V Verbose output
Notes:
For MONTHLY schedules give the DAY as a number 1 - 31 (default=1)
For the system account, /RU username can be written as ””, “NT AUTHORITY\SYSTEM” or
“SYSTEM”, a Password is not required. The system account has full access to the local machine but has
no permissions on any other machines (or mapped drives) across the Network.
/SC schedule The schedule frequency.
Valid schedules: MINUTE,HOURLY,DAILY,WEEKLY,MONTHLY,
ONCE,ONSTART,ONLOGON,ONIDLE.
/MO modifiers allow finer control:
MINUTE: 1 - 1439 minutes.
HOURLY: 1 - 23 hours.
DAILY: 1 - 365 days.
WEEKLY: 1 - 52 weeks.
ONCE: No modifiers.
ONSTART: No modifiers.
ONLOGON: No modifiers.
ONIDLE: No modifiers.
MONTHLY: 1 - 12, or FIRST, SECOND, THIRD, FOURTH, LAST, LASTDAY.
Power Saving
The property for “Wake up the machine to run this task” cannot be set
using schtasks, but this property is essential if you need the task to run on a
machine that has PowerSaving enabled.
To work around this, create a task on one computer using the control panel
GUI. This will create a .job file in C:\%windir%\Tasks\
To replicate the scheduled task onto other machines copy the .JOB file to
C:\%windir%\Tasks on each machine.
This techique will not retain any system account credentials, so if you need to
run the tasks under System, run the following after copying the .JOB file:
SCHTASKS /CHANGE /RU “NT Authority\System” /TN “Yourtaskname”
Examples:
Create a task to run at 11 pm every weekday
SCHTASKS /Create /SC weekly /D MON,TUE,WED,THU,FRI /TN MyDailyBackup /ST
23:00:00 /TR c:\backup.cmd /RU MyDomain\MyLogin /RP MyPassword
SCLIST (*)
List Services
Syntax
SCLIST [options] [ComputerName]
Key
-r : Display only running services
-s : Display only stopped services
ComputerName : The computer running the services
(default = %ComputerName% )
SET
Display, set, or remove CMD environment variables. Changes made with
SET will remain only for the duration of the current CMD session.
Syntax
SET variable
SET variable=string
SET /A variable=expression
SET “variable=”
SET /P variable=[promptString]
SET “
Key
variable : A new or existing environment variable name
string : A text string to assign to the variable.
expression: : Arithmetic Sum
Also see SetX, VarSearch and VarSubstring for more advanced variable manipulation.
Variable names are not case sensitive but the contents can be. Variables
can contain spaces.
The number one problem people run into with SET is having extra
spaces around either the variable name or the string, SET is not forgiving of
extra spaces like many other scripting languages.
The CMD shell will fail to read an environment variable if it contains
more than 8,191 characters.
To display current variables:
Type SET without parameters to display all the current environment variables.
Type SET with a variable name to display that variable SET _department
or use ECHO: ECHO [%_department%]
The SET command invoked with a string (and no equal sign) will display a
wildcard list of all matching variables
The /P switch allows you to set a variable equal to a line of input entered
by the user.
The PromptString is displayed before the user input is read. The PromptString
can be empty.
The CHOICE command is an alternative to SET /P
To place the first line of a file into a variable:
Set /P _MyVar=<MyFilename.txt
CALL SET
SET can be CALLed allowing a variable substring to be evaluated:
SET start=10
SET length=9
SET string=The quick brown fox jumps over the lazy dog
CALL SET substring=%%string:~%start%,%length%%%
ECHO (%substring%)
Type SET with just the variable name and an equals sign:
SET _department=
A variable can contain spaces and also the variable name itself may contain
spaces, therefore the following assignment:
SET my var=MyText
will create a variable called “my var”
Similarly
SET _var =MyText
will create a variable called “_var ” - note trailing space
To avoid problems with extra spaces appearing in your output, issue SET
statements in parentheses, like this
Note: if you wanted to actually include a bracket in the variable you need to
use an escape character.
The SET command will set ERRORLEVEL to 1 if the variable name is not
found in the current environment.
This can be detected using the IF ERRORLEVEL command
Arithmetic expressions (SET /a)
SET /a calculations
Enclose any logical expressions in “quotes”
Several calculations can be put on one line if separated with commas.
The octal notation can be confusing - all numeric values that start with zeros
are treated as octal but 08 and 09 are not valid numbers because 8 and 9 are
not valid octal digits.
This is often a cause of error when performing date arithmetic. For example
SET /a _day=07 will return the value=7, but SET /a _day=09 will return an
error.
Permanent Changes
Changes made using the SET command are NOT permanent, they apply to
the current CMD prompt only and remain only until the CMD window is
closed.
To permanently change a variable at the command line use SetX
or in the GUI - Control Panel, System, Environment, System/User Variables
Changing a variable permanently with SetX will not affect any CMD prompt
that is already open.
Only new CMD prompts will get the new setting.
You can of course use SetX in conjunction with SET to change both at the
same time, but neither SET or SetX will affect other CMD sessions that are
already running. When you think about it - this is a good thing.
Autoexec.bat
Any SET statement in c:\autoexec.bat may be parsed at boot time
Variables set in this way are not available to 32 bit gui programs - they won’t
appear in the control panel.
They will appear at the CMD prompt.
If autoexec.bat CALLS any secondary batch files, the additional batch files
will NOT be parsed at boot.
This behaviour can be useful on a dual boot PC.
If Command Extensions are disabled all SET commands are disabled
other than simple assignments like:
_variable=MyText
SETLOCAL
Set options to control the visibility of environment variables in a batch
file.
Syntax
SETLOCAL
SETLOCAL EnableDelayedExpansion
SETLOCAL EnableExtensions | DisableExtensions
Key
EnableDelayedExpansion Expand variables at execution time rather than at parse time.
EnableExtensions Attempt to enable Command extensions.
DisableExtensions Attempt to disable Command extensions.
SETLOCAL on it’s own, usually at the start of a batch file, will begin
localisation of Environment Variables.
Issuing a SETLOCAL command, the batch script will inherit all current
variables from the master environment/session.
Issuing an ENDLOCAL command will restore any environment
variables present before the SETLOCAL was issued.
If a batch script does not use SETLOCAL and ENDLOCAL then all
variables will be Global, i.e. visible and modifiable by other scripts.
Although global variables are easy to work with they are not good
practice - for example if you have several batch scripts dealing with filenames
(and these scripts may be CALLing one another), the first script may have a
variable called _filename, the second script a different variable called file-
name (a different name to avoid conflicting with the first script) a third script
now needs something like file_name this quickly becomes very difficult to
manage.
With local variables you are free to use the same variable names in
multiple batch scripts - there is no conflict because the local variables are not
visible to any other script.
Local Variables can be passed from one batch routine to another with the
ENDLOCAL command.
EnableDelayedExpansion
Setting EnabledDelayedExpansion will cause each variable to be
expanded at execution time rather than at parse time.
EnableDelayedExpansion is Disabled by default.
Overloading a variable
SETLOCAL can be used more than once in the same batch file so that
multiple values can be stored in the same Environment Variable. To keep
track of variable definitions, SETLOCAL and ENDLOCAL statements should
be paired.
@echo off
SETLOCAL
::Standard commission
SET _Commission=20
echo %_Commission%
::Premium commission
SETLOCAL
set _Commission=30
echo %_Commission%
DISABLEEXTENSIONS
Command Extensions are enabled by default, there is rarely any need to
disable them.
If Command Extensions are permanently disabled or if a script is
running under the Windows 95 command processor command.com then
SETLOCAL ENABLEEXTENSIONS will not be able to restore them.
Errors
SETLOCAL will set an ERRORLEVEL if given an argument: It will be
zero if one of the two valid arguments is given and one otherwise.
SETX can be used to set Environment Variables for the machine or currently
logged on user:
SETX Variable Value
Key:
-m Set the value in the Machine environment (HKLM)
Default is User (HKCU)
SetX can also be used in modes to edit the Registry or edit CR-LF text
files, (like win.ini) for most purposes these tasks are better done with other
tools in the resource kit, e.g. the REG command.
Because SetX writes variables to the master environment in the registry.
Edits will only take effect when a new command window is opened - they do
not affect the current command session.
Deleting variables
A value of ”” (empty quotes) will appear to delete the variable - it’s not shown
by SET but the variable name will remain in the registry. Either use the GUI
(recommended) or delete the value from the registry with REG
REG delete HKCU\Environment /V _myvar
Deleting a variable with REG does not take effect until next logon due to
caching of registry data. The type is REG_EXPAND_SZ.
Examples:
Set the variable _myTimeZone in both the immediate user session and the
permanent environment:
SET _myTimeZone=GMT
SetX _myTimeZone GMT
Machine variables
These are stored on the machine and won’t follow a users roaming
profile.
To set a machine variable (-m) requires Administrator rights.
Create a machine variable:
SetX _myvar COMPAQ -m
Delete a machine variable:
REG delete “HKLM\SYSTEM\CurrentControlSet\Control\Session
Manager\Environment” /V _myvar
Share.vbs (*)
List or edit a file share or print share (on any computer)
Although missing from recent Resource Kits, this VBS script does still
work under recent versions of Windows. The preferred method for creating
shares is the RMTShare command, which can also grant permissions.
Syntax:
List Shares
Share.vbs /L [/S <server>] [/U <username>] [/W <password>] [/O <outputfile>]
Create a Share
Share.vbs /C /N <name> /P <path> [/T <type>] [/V <description>]
[/S <server>] [/U <username>] [/W <password>] [/O <outputfile>]
Delete a Share
Share.vbs /D /N <name>
[/S <server>] [/U <username>] [/W <password>] [/O <outputfile>]
Key:
/L List
/C Create
/D Delete
/N name Name of the share to be created or deleted.
/P path Path of the share to be created.
/v description A description for the share.
/T type Type of the share to be created. (Disk, Printer, IPC or Special)
/S server A machine name.
/U username The current user’s name.
/W password Password of the current user.
/O outputfile Output file name.
Examples:
e.g. -u natn)
-l logfile : Save any error messages in the specified file
Example
@ECHO off
MD %userprofile%”\start menu\programs\MY APP”
SHORTCUT -f -t C:\MyApp.exe -n %userprofile%”\start menu\programs\MY APP\MY APP”
For Windows XP and more recent systems, you are better off using a
little .vbs script, as WSH is built-in from XP onwards, call the script like so:
CSCRIPT C:\myshortcut.vbs
Optional sections in the VBscript below are commented out:
Set oWS = WScript.CreateObject(“WScript.Shell”)
sLinkFile = “C:\MyShortcut.LNK”
Set oLink = oWS.CreateShortcut(sLinkFile)
oLink.TargetPath = “C:\Program Files\MyApp\MyProgram.EXE”
‘ oLink.Arguments = ””
‘ oLink.Description = “MyProgram”
‘ oLink.HotKey = “ALT+CTRL+F”
If a shortcut to a file breaks because the destination file has moved, then by
default Windows will attempt to automatically locate the shortcut destination
by performing a search (this only applies to NTFS partitions). To turn this off
- add a DWORD value of 1 to the registry:
HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
NoResolveTrack=1
HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
“LinkResolveIgnoreLinkInfo”=1
Favourites
Often confused with shortcuts, Internet Explorer Favourite (.URL) files are
simple text files which you can create with a few ECHO statements.
SHOWGRPS (*)
List the Workgroups a user has joined.
Syntax
SHOWGRPS domain\username
SHOWGRPS username
SHOWGRPS exampledomain\user05
SHOWMBRS (*)
List all the users who are members of a Workgroup.
Syntax
SHOWMBRS domain\Workgroup
SHOWMBRS Workgroup
Example:
SHOWMBRS wg_finance
When using this command to reboot a server, the shutdown process will
normally allow 30 seconds to ensure each running service has time to stop.
Services are shutdown in alphabetical order. The shutdown may be done
made faster if the services are first halted in a specific order using NET STOP
or SC.
Reason codes:
E = Expected
U = Unexpected
P = Planned (C = customer defined)
Type Major Minor Title
U 0 0 Other (Unplanned)
E 0 0 Other (Unplanned)
E P 0 0 Other (Planned)
U 0 5 Other Failure: System Unresponsive
E 1 1 Hardware: Maintenance (Unplanned)
E P 1 1 Hardware: Maintenance (Planned)
E 1 2 Hardware: Installation (Unplanned)
E P 1 2 Hardware: Installation (Planned)
P 2 3 Operating System: Upgrade (Planned)
E 2 4 Operating System: Reconfiguration (Unplanned)
E P 2 4 Operating System: Reconfiguration (Planned)
P 2 16 Operating System: Service pack (Planned)
2 17 Operating System: Hot fix (Unplanned)
P 2 17 Operating System: Hot fix (Planned)
2 18 Operating System: Security fix (Unplanned)
P 2 18 Operating System: Security fix (Planned)
E 4 1 Application: Maintenance (Unplanned)
E P 4 1 Application: Maintenance (Planned)
E P 4 2 Application: Installation (Planned)
E 4 5 Application: Unresponsive
E 4 6 Application: Unstable
U 5 15 System Failure: Stop error
E 5 19 Security issue
U 5 19 Security issue
E P 5 19 Security issue
E 5 20 Loss of network connectivity (Unplanned)
U 6 11 Power Failure: Cord Unplugged
U 6 12 Power Failure: Environment
P 7 0 Legacy API shutdown
Examples
Shutdown the local system immediately:
SHUTDOWN /s
Restart the local system in 60 seconds time and specify the reason
“Application: Installation (Planned)” :
SHUTDOWN /r /t:60 /d P:4:2
Restart the remote system server64 and specify the reason “Security Fix,
Planned”
SHUTDOWN /r /m \server64 /d P:2:17
SLEEP.exe (*)
Delay execution for a few seconds/minutes (for use within a batch file.)
Syntax
SLEEP time
Key
time The number of seconds to pause
For example:
To pause for an hour before running the next command in a batch file:
SLEEP 3600
Alternative
A delay can also be produced by the PING command with a loopback
address, in tests this consumes less processor time than Sleep.exe or
Timeout.exe:
slmgr.vbs (Windows7/2008)
Software Licensing Management Tool. Windows Activation and Key
Management Service (KMS)
Syntax
slmgr [MachineName [Username Password]] [Option]
Key
machinename The machine to administer, by default the current local machine.
username An administrator equivalent user account for the remote computer.
password The password for the user account on the remote computer.
/ato Activate Windows license and product key against Microsoft’s server.
/atp Confirmation_ID Activate Windows with user-provided Confirmation ID
/ckms Clear the name of KMS server used to default and port to default.
/cpky Clear product key from the registry (prevents disclosure attacks)
/dli Display the current license information with activation
status and partial product key.
/dlv Verbose, similar to -dli but with more information.
/dti Display Installation ID for offline activation
/ipk Key Enter a new product key supplied as xxxxx-xxxxx-xxxxx-xxxxx-xxxxx
/ilc License_file Install license
/rilc Re-install system license files
/rearm Reset the evaluation period/licensing status and activation state of the machine
/skms activationservername:port
Set the Volume Licensing KMS server and/or the port used for KMS activation
(where supported by your Windows edition)
/skhc Enable KMS host caching (default), this blocks the use of DNS priority and
weight after the initial discovery of a working KMS host.
If the system can no longer contact the working KMS host, discovery will be attempted again.
/ckhc Disable KMS host caching. This setting instructs the client to use DNS auto-discovery
each time it attempts KMS activation (recommended when using priority and weight)
/sai interval
Sets the interval in minutes for unactivated clients to attempt KMS connection.
The activation interval must be between 15 minutes and 30 days, although the default (2 hours)
is recommended.
The KMS client initially picks up this interval from the registry but switches to the KMS
setting after the first KMS response has been received.
/sri interval
Sets the renewal interval in minutes for activated clients to attempt KMS connection.
The renewal interval must be between 15 minutes and 30 days.
This option is set initially on both the KMS server and client sides.
The default is 10080 minutes (7 days).
/spri Set the KMS priority to normal (default).
/cpri Set the KMS priority to low.
Use this option to minimize contention from KMS in a co-hosted environment.
Note that this could lead to KMS starvation, depending on what other applications
or server roles are active. Use with care.
/sprt port
Sets the port on which the KMS host listens for client activation requests. The default TCP port is
1688.
/sdns Enable DNS publishing by the KMS host (default).
/cdns Disable DNS publishing by the KMS host.
/upk Uninstall current installed product key and return license status back to trial state.
/xpr Show the expiry date of current license (if not permanently activated)
Token-based activation:
/lil List the installed token-based activation issuance licenses.
/ril ILID ILvID
SOON.exe (*)
Schedule a command to run in the near future (calls the AT command)
Syntax
SOON [\computername] delay [/interactive] “command”
SOON /i:[on|off]
Key
delay : When the command should run, in SECONDS from now.
default=5
/interactive : Allows any user to see the job as it runs,
this allows testing and monitoring of the
command.
You can specify /interactive as just /i
computername : the UNC name of a remote machine
/i:on : Make /interactive the default behaviour
use SOON /i:off to restore normal behaviour
SORT
Sort will accept a redirected or piped file input and TYPE the file, sorted
line by line.
Syntax
SORT [options]
Options
/R : Reverse sort order (Z to A, 9 to 0)
/+n : Sort the file ignoring the first ‘n’ characters in each row.
The default is to sort using all the chars in each row.
/L[OCALE] locale
Override the system default locale with
The “C” locale yields a faster
collating sequence.
The sort is always case insensitive.
/M[EMORY] kilobytes
The amount of RAM to use for the sort.
The best performance is usually achieved by
not specifying a memory size.
SORT will only create a temporary file
when required by limitations in available memory.
/REC[ORD_MAXIMUM] characters
The maximum number of characters in a row or record
(default 4096, maximum 65535)
[drive:][pathname]
The file to be sorted.
If not specified, the standard input is sorted.
Specifying an input file is faster than
redirecting the same file as standard input.
/T[EMPORARY] [drive:][path]
The path of the directory to hold
SORT’s working storage, in case the data
does not fit in RAM. The default is %temp%
/O[UTPUT] [drive:][pathname]
The file where the sorted input is to be stored.
If not specified, the data is written to standard output.
Specifying an output file is faster than redirecting
standard output to a file.
command | SORT
START
Start a specified program or command in a separate window.
Syntax
START “title” [/Dpath] [options] “command” [parameters]
Key:
title : Text for the CMD window title bar (required)
path : Starting directory
command : The command, batch file or executable program to run
parameters : The parameters passed to the command
Options:
/MIN : Minimized
/MAX : Maximized
/WAIT : Start application and wait for it to terminate
/LOW : Use IDLE priority class
/NORMAL : Use NORMAL priority class
/HIGH : Use HIGH priority class
/REALTIME : Use REALTIME priority class
/B : Start application without creating a new window. In this case
^C will be ignored - leaving ^Break as the only way to
interrupt the application
/I : Ignore any changes to the current environment.
Options for 16-bit WINDOWS programs only
/SEPARATE Start in separate memory space (more robust)
/SHARED Start in shared memory space (default)
Notes:
Always include a TITLE this can be a simple string like “My Script” or
just a pair of empty quotes ””
According to the Microsoft documentation, the title is optional, but you may
have problems if it is omitted.
Document files may be invoked through their file association just by
typing the name of the file as a command.
e.g. START ”” WORD.DOC would launch the application associated with the
.DOC file extension
Examples
START “My Login Script” /Min Login.cmd
START ”” /wait MySlowProgram.exe
Printers
A new printer can be installed very quickly (and the driver downloaded) with
the command:
START \print_server\printer_name
@echo off
start /wait /b First.exe
start /wait /b Second.exe
start /wait /b Third.exe
Create a shortcut to this batch file and place it on the Start menu or desktop.
Set it to run minimized.
When the user double-clicks the shortcut, <First.exe> runs.
When <First.exe> terminates, <Second.exe> runs
When <Second.exe> terminates, <Third.exe> runs
.COM;.EXE;.BAT;.CMD
Notice the syntax is the same as the PATH variable, with semicolons
separating the different elements.
SU (*)
Switch User.
Syntax
SU “[cmdline]” [domain] [[Winsta\]Desktop] [options]
Key
cmdline The command to run (default =%comspec%)
domain The domain for the user account (‘.’ = local m/c)
Winsta\Desktop The profile to load (default = current)
Options
-cb console bypass
-dn do not switch to new desktop
-g GUI option
-l load the .Default user registry hive
-w use current registry hive
-e Inherit parent environment
-b batch logon
-i interactive logon
-s service logon
-n network logon
-v verbose
SUBINACL.exe (*)
Download latest version (2004)
Display or modify Access Control Entries (ACEs) for file and folder
Permissions, Ownership and Domain.
Access Control Lists apply only to files stored on an NTFS formatted drive,
each ACL determines which users (or groups of users) can read or edit the
file. When a new file is created it normally inherits ACL’s from the folder
where it was created.
Syntax
SUBINACL [/noverbose] /object_type object_name [/action=parameter] [/help]
Key
object_type: service e.g. /service Messenger \ServerName\Messenger
keyreg e.g. /keyreg HKEY_CURRENT_USER\Software
/keyreg \Srv\HKEY_LOCAL_MACHINE\KeyPath
file e.g. /file *.obj /file c:\test.txt
/file \ServerName\Share\Path
subdirectories manipulate files in specified directory and all subdirectories
object_name : This will vary according to the object_type - see the examples above
action : setowner=owner
will change the owner of the object e.g. /setowner=MyDomain\Administrators
replace=SamName\OldAccount=DomainName\New_Account
will replace all ACE (Audit and Permissions) in the object
e.g. /replace=MyOldDomain\Finance=NEWDOM\Finance
changedomain=OldDomainName=NewDomainName
will replace all ACEs with a Sid from OldDomainName
with the equivalent Sid found in NewSamServer
e.g. /changedomain=MyOldDomain=NEWDOMAIN
This option requires a trust relationship with the server containing the object.
subinacl can do everything that cacls and xcacls can do and more besides.
List permissions to log file:
subinacl /noverbose /nostatistic /outputlog=my.log /subdirectories
“C:\Program Files\My Folder\*.*” /display
Restore Permissions:
subinacl /nostatistic /playfile my.log
Change owner :
subinacl /file C:\demofile.doc /setowner=MYDOMAIN\BillG
SUBST
Substitute a drive letter for a network or local path.
Syntax
SUBST drive_letter: path
SUBST
SUBST drive_letter: /D
Key
SUBST with no parameters will display current SUBST drives
/D : Delete the drive_letter substitution.
Compared to mapping a drive with NET USE the SUBST command
allows mapping to a subfolder of a drive share - for the storage of user
profiles this reduces the number of shares you need to create on the server.
Notes
Under NT 4 SUBST’ed drives could be disconnected using the Explorer GUI
- this was fixed in Windows 2000.
In Windows 2000 (and above) you may have problems creating, accessing
and deleting drive mappings with SUBST.
However under Win 2K/XP the functionality of the NET USE command is
improved so you can now do
NET USE g: \server\share\folder1\folder2
If the network resource is unavailable (ie the server is down) SUBST will
continually retry - unlike NET USE which will try to connect once and fail -
depending on your application this may be a good or a bad thing - a subst
drive that is not available will badly impact performance of most applications.
Notice that when SUBST is used against a local shared folder, it will create a
RECYCLER for that drive. The RECYCLER is not removed when the drive
substitution is removed, but can be deleted manually.
SYSTEMINFO
List system configuration
Syntax
SYSTEMINFO [/S system [/U username [/P [password]]] ]
[/FO format] [/NH]
Key:
/S system Remote system to connect to.
/U [domain\]user User context under which to execute.
/P [password] Password for the given user (will prompt if omitted)
/FO format Output format: TABLE, LIST or CSV
/NH No “Column Header” in the Table/CSV output
TASKLIST
TaskList displays all running applications and services with their Process
ID (PID) This can be run on either a local or a remote computer.
Syntax
tasklist options
Options:
/s computer Name or IP address of a remote computer
don’t use backslashes. Default = local computer.
/u domain\user [/p password]]
Run under a different account
/svc List information for each process without truncation.
Valid when /fo=TABLE. Cannot be used with /m or /v
/m [ModuleName]
Show the processes that include the given module.
/v Verbose task information
/fo {TABLE|LIST|CSV}]
Output format, the default is TABLE.
/nh No Headers in the output (does not apply to LIST output)
/fi FilterName [/fi FilterName2 [ … ]]
Apply one of the Filters below:
Imagename eq, ne String
PID eq, ne, gt, lt, ge, le Positive integer.
Session eq, ne, gt, lt, ge, le Any valid session number.
SessionName eq, ne String
Status eq, ne RUNNING | NOT RESPONDING
CPUTime eq, ne, gt, lt, ge, le Time hh:mm:ss
MemUsage eq, ne, gt, lt, ge, le Any valid integer.
Username eq, ne User name ([Domain\]User).
Services eq, ne String
Windowtitle eq, ne String
Modules eq, ne String
Examples:
List the services running under each process:
TASKLIST /svc
List the services running under each SvcHost process:
TASKLIST /FI “imagename eq svchost.exe” /svc
List the services running now:
TASKLIST
End one or more processes (by process id or image name).
Syntax
TASKKILL [/S system [/U username [/P [password]]]]
{ [/FI filter] [/PID processid | /IM imagename] } [/F] [/T]
Options
/S system The remote system to connect to.
/U [domain\]user The user context under which
the command should execute.
/P [password] The password. Prompts for input if omitted.
/F Forcefully terminate the process(es).
/FI filter Display a set of tasks that match a
given criteria specified by the filter.
/PID process id The PID of the process to be terminated.
/IM image name The image name of the process to be terminated.
Wildcard ‘*’ can be used to specify all image names.
/T Tree kill: terminates the specified process
and any child processes which were started by it.
Filters Apply one of the Filters below:
Imagename eq, ne String
PID eq, ne, gt, lt, ge, le Positive integer.
Session eq, ne, gt, lt, ge, le Any valid session number.
Status eq, ne RUNNING | NOT RESPONDING
CPUTime eq, ne, gt, lt, ge, le Time hh:mm:ss
MemUsage eq, ne, gt, lt, ge, le Any valid integer.
Username eq, ne User name ([Domain\]User).
Services eq, ne String The service name
Windowtitle eq, ne String
Modules eq, ne String The DLL name
Examples:
Examples:
TASKKILL /S system /F /IM notepad.exe /T
TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
TASKKILL /F /IM notepad.exe /IM mspaint.exe
TASKKILL /F /FI “PID ge 1000” /FI “WINDOWTITLE ne untitle*”
TASKKILL /F /FI “USERNAME eq NT AUTHORITY\SYSTEM” /IM notepad.exe
TASKKILL /S system /U domain\username /FI “USERNAME ne NT*” /IM *
TASKKILL /S system /U username /P password /FI “IMAGENAME eq note*”
TIME
Display or set the system time.
Syntax
TIME [new_time]
TIME
TIME /T
key
new_time : The time as HH:MM
TIME with no parameters will display the current time and prompt
for a new value. Pressing ENTER will keep the same time.
/T : Just display the time, formatted according to the current Regional settings.
Time Formatting
In Control Panel, Regional settings a Time Appearance can be set. This can
be used to change the separator, and the number of characters used to display
hours and minutes.
ECHO.| TIME will display the time, including seconds and hundredths of a
second
The time separator and the Country Code are user settings in the registry:
To read the Country Code replace sTime in the above with iCountry.
The time formats for different country codes are as follows:
Country or language CountryCode Date format Time format
United States 001 01/03/1994 5:35:00.00p
Czechoslovakia 042 03.01.1994 17:35:00
France 033 03.01.1994 17:35:00
Germany 049 03.01.1994 17:35:00
Latin America 003 03/01/1994 5:35:00.00p
International English 061 03/01/1994 17:35:00.00
Portugal 351 03-01-1994 17:35:00
Finland 358 3.1.1994 17.35.00
Switzerland 041 03.01.94 17 35.00
Norway 047 03.01.94 17:35:00
Belgium 032 03/01/94 17:35:00
Brazil 055 03/01/94 17:35:00
Italy 039 03/01/94 17.35.00
United Kingdom 044 03/01/94 17:35:00.00
Denmark 045 03-01-94 17.35.00
Netherlands 031 03-01-94 17:35:00
Spain 034 3/01/94 17:35:00
Hungary 036 1994.01.03 17:35:00
Canadian-French 002 1994-01-03 17:35:00
Poland 048 1994-01-03 17:35:00
Sweden 046 1994-01-03 17.35.00
TIMEOUT.exe (*)
Delay execution for a few seconds/minutes (for use within a batch file.)
Syntax
TIMEOUT delay
Key
delay Delay in seconds (between -1 and 100000) to wait before continuing.
The value -1 causes the computer to wait indefinitely for a keystroke
(like the PAUSE command)
TITLE
Change the title displayed above the CMD window.
Syntax
TITLE [string]
Key
string : The title for the command prompt window.
The default title is %comspec% however, since the title can also be defined in
a program shortcut, the title is usually set to “Command Prompt”
To change the title for the duration of a command use:
TITLE This is the initial title text
CMD /c MyBatchFile.cmd
…
Show the command, command line, working directory, memory usage and
DLLs for each running task. This command is no longer supplied with recent
versions of the Windows resource kit, having been replaced by TASKLIST,
however if you can find a copy Tlist does have the advantage of showing the
full path of the process.
Syntax
TLIST
TLIST -t
TLIST pid
TLIST -t pid
TLIST pattern
TLIST -t pattern
Key
-t : Show Task dependencies in Tree form
pid : List module information for this task
if no PID is given - all Tasks are listed
pattern : A complete task name or expression pattern (e.g. CMD.*)
if a pattern is given it will match against
task names or window titles.
Example:
The following batch file will show the full path of all running programs.
@ECHO off
FOR /f “tokens=1” %%G in (‘tlist’) DO (call :s_item %%G)
GOTO :eof
:s_item
tlist %1 | find “CmdLine”
Use the optional argument /t to specify a date other than the current time.
( four-digit years, two-digit months, days, hours, minutes, seconds)
Example
To set the date to 7:30 am 1st October 2015
TOUCH /t 2015 10 01 07 30 00 MyFile.txt
TRACERT
Trace Route - Find the IP address of any remote host. TRACERT is
useful for troubleshooting large networks where several paths can be taken to
arrive at the same point, or where many intermediate systems (routers or
bridges) are involved.
Syntax
TRACERT [options] target_name
Key
target_name The HTTP or UNC name of the host
Options:
-d Do not resolve addresses to hostnames.
(avoids performing a DNS lookup)
-h max_hops Maximum number of hops to search for target.(default=30)
-j host-list Trace route along given host-list.
up to 9 hosts in dotted decimal notation, separated by spaces.
-w timeout Wait timeout milliseconds for each reply.
Examples
TRACERT www.doubleclick.net
TRACERT 123.45.67.89
TRACERT local_server
TsShutDn
Remotely shut down or reboot a terminal server. If the computer
supports software control of AC power this command may be used to power
off the server.
Syntax
TSSHUTDN [WaitTime] [/server:ServerName] [/reboot] [/powerdown]
[/delay:LogOffDelay] [/v]
Key
WaitTime An amount of time (in seconds) to wait after notifying users before logging off
all users from their sessions. Default = 60 seconds.
/server The terminal server to shut down.
If unspecified, the current terminal server is shut down.
/reboot Reboot the terminal server after user sessions are ended.
/powerdown Turn off the terminal server if the computer supports software control of AC power.
/delay The amount of time to wait after logging off users from their sessions,
before ending all processes and shutting down the terminal server.
Default = 30 seconds.
/v Display verbose information about the actions being performed.
/? Display help.
TSSHUTDN /v
End all client sessions 5 minutes after notification, and then 1 minute after all
the users are logged off, shutdown and restart the terminal server:
TSSHUTDN 300 /reboot /delay:60 /v
On the terminal server named “Server64”, end all client sessions 2
minutes after notification, and then 20 seconds after all the users are logged
off, shutdown and restart the terminal server:
TSSHUTDN 120 /server:server64 /delay:20 /v
TYPE
Display the contents of one or more text files, convert Unicode to ANSI.
Syntax
TYPE [drive:]pathname(s)
If more than one file is specified the filenames are included in the output.
If a wildcard is used the filenames are not displayed.
When using redirection to SORT a file the TYPE command is used implicitly
For example:
TypePerf.exe
Write performance data to the command window or to a log file.To stop
Typeperf, press CTRL+C.
Syntax
typeperf counter [counter …] [options]
typeperf -cf filename [options]
typeperf -q [object] [options]
typeperf -qx [object] [options]
Key
counter The Performance counters to monitor.
-f {CSV|TSV|BIN|SQL} Output file format. Default is CSV.
-cf filename File containing performance counters to monitor, one per line.
-si [[hh:]mm:]ss Time between samples. Default is 1 second.
-o filename Path of output file or SQL database.
Default is STDOUT.
-q [object] List installed counters (no instances).
To list counters for one object,
include the object name, such as Processor.
-qx [object] List installed counters with instances.
To list counters for one object,
include the object name, such as Processor.
-sc samples Number of samples to collect. Default is
to sample until CTRL+C.
-config filename Settings file containing command options.
-s computer_name Server to monitor if no server is specified in the counter path.
-y Answer yes to all questions without prompting.
-? Display context sensitive help.
VER
Display the current operating system version.
Syntax
VER
VERIFY
To check that files are saved to disk correctly; the system can re-read the
disk when saving and verify (compare) with the data in memory.
Syntax
VERIFY [ON | OFF]
VOL
Display the volume label of a disk.
Syntax
VOL [drive:]
If the drive exists, VOL will display it’s disk label and serial number and
will return an %ERRORLEVEL% of 0.
If the drive does not exist VOL will return an %ERRORLEVEL% of 1.
If the drive is a CD/DVD drive with no disk loaded then VOL will return
“The device is not ready” and will return an %ERRORLEVEL% of 1.
Signal names cannot exceed 225 characters. Valid characters include a-z,
A-Z, 0-9, the SignalName is not case-sensitive.
If the command line includes /s Computer, the signal will be broadcast
only to the specified system rather than all the computers across the domain.
On large domains or wide area networks this will reduce unnecessary network
traffic.
To cancel WAITFOR before its timeout has been reached, either launch
Waitfor /si signal from a separate command-prompt or KILL the session.
You can run multiple instances of WAITFOR on a single computer, but
each instance must wait for a different signal. Only one instance of
WAITFOR can wait for a given signal on a given computer. Computers can
only receive signals if they are in the same domain as the computer sending
the signal.
Batch scripts including WAITFOR may be run as Scheduled tasks under
the SYSTEM account.
Typical WAITFOR applications include waiting for large ROBOCOPY
jobs to complete, restarting services across a cluster/farm, FTP or BITS
downloads, compiling software builds etc.
Examples
Wait for 60 seconds or until the “simon” signal is received on the local
computer:
C:\> waitfor /t 60 simon
Activate the “simon” signal on the local computer:
C:\> waitfor /s %computername% /si simon
Wait for 1 hour or until the “backupComplete” signal is received on the
local computer:
C:\> waitfor /t 3600 BackupComplete
Activate the “backupComplete” signal on the computer Server64:
C:\> waitfor /s Server64 /si backupComplete
ECHO %USERDOMAIN%\%USERNAME%
One exception to this is when using RUNAS /env , e.g. if my username
is Simon:
c:>whoami
example\JDoe
WHOAMI /all - shows all permissions and group memberships.
If either path is not specified it will default to the current directory (or a
matching file in the current directory)
If nothing is specified, the GUI will appear - select files to compare with
the menus.
White background = parts common to both files.
Red background = parts that belong to the file listed on the left .
Yellow background = parts that belong to the file listed on the right .
Registry files (exported with regedit) can also be compared. Also see the
help file Windiff.hlp.
WINMSDP.exe (*)
Windows NT diagnostics II
Reports: Memory use, Services, Devices, IRQ’s Ports, Environment variables,
Network (rights, transport, stats), Hardware including Display adapter.
Syntax
WINMSDP option
Key (only one option can be used)
/a : ALL prints everything
/e : environment
/d : drives
/i : interrupt resources
/m : memory
/n : network
/o : OS version
/p : port resources
/r : drivers
/s : services
/u : DMA resources
/w : hardware
/y : memory resources
WINRM
Windows Remote Management
Secure communication with local and remote computers using web services.
Syntax
winrm g[et] | s[et] | c[reate] | d[elete] | e[numerate] |
i[nvoke] | id[entify] | quickconfig | configSDDL | helpmsg
Retrieve instances of RESOURCE_URI:
winrm get RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] …]
winrm get winrm/config
winrm get winrm/config/client
winrm get winrm/config/service
Modify settings in RESOURCE_URI:
winrm set RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] …]
[@{KEY=“VALUE”[;KEY=“VALUE”]}]
[-file:VALUE]
Spawn an instance of RESOURCE_URI:
winrm create RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] …]
[@{KEY=”VALUE“[;KEY=”VALUE“]}]
[-file:VALUE]
Control remote access to WinRM resources, launch a GUI to edit security settings.
winrm configsddl RESOURCE_URI
Enable this machine for remote management.
winrm quickconfig [-quiet] [-transport:VALUE]
This will start the WinRM service, set the service to auto start, create
a listener and enable an http firewall exception for WS-Management traffic
-q[uiet] Don’t prompt for confirmation.
-transport:VALUE Perform quickconfig for either http or https. Default = http.
List instances of RESOURCE_URI:
winrm enumerate RESOURCE_URI [-ReturnType:Value] [-Shallow]
[-BasePropertiesOnly] [-SWITCH:VALUE [-SWITCH:VALUE] …]
Remove an instance of RESOURCE_URI:
winrm delete RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] …]
Execute method specified by ACTION on target object specified by RESOURCE_URI
winrm invoke ACTION RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] …]
[@{KEY=”VALUE“[;KEY=”VALUE“]}]
[-file:VALUE]
Display error message associate with the error code.
winrm helpmsg errorcode
Key
-a[uthentication]:VALUE
The authentication mechanism to use when communicating
with the remote machine.
-defaultCreds Allow implicit credentials when Negotiate is used.
Remote HTTPS operations for trusted machines.
-dialect:VALUE Dialect of the filter expression for enumeration or fragment.
Example: Use a WQL query
-dialect:http://schemas.microsoft.com/wbem/wsman/1/WQL
Example: Use XPATH for filtering with enumeration or fragment get/set.
-dialect:http://www.w3.org/TR/1999/REC-xpath-19991116
-encoding:VALUE The encoding type when talking to remote machine (see -remote).
Possible options are “utf-8” (the default) or “utf-16”.
-f[ormat]:FORMAT The format of output. FORMAT can be “xml”,
“pretty” (better formatted XML), or “text”.
-r[emote]:VALUE Specify the identifier of a remote endpoint/system.
This may be a simple host name or a complete URL.
-skipCAcheck The certificate issuer need not be a trusted root authority.
Remote HTTPS operations for trusted machines.
-skipCNcheck The certificate common name (CN) of the server need not match
the hostname of the server. HTTPS operations for trusted machines.
-skipRevocationcheck Do not check the revocation status of the server certificate.
Remote HTTPS operations for trusted machines.
-SPNPort Append port number to the Service Principal Name (SPN) of the
remote server.
Service principal name is used when Negotiate or Kerberos authentication
mechanism is in use.
-timeout:MS Timeout in milliseconds. Limits duration of corresponding operation.
Default timeout can be configured by:
winrm set winrm/config @{MaxTimeoutms=“XXXXXX”}
Where XXXXXX is an integer indicating milliseconds.
-file:VALUE
@{KEY=”VALUE“[;KEY=”VALUE“]}
Input from an XML file or via key/value pairs.
Applies to set, create, and invoke operations
-fragment:VALUE Specify a section inside the instance XML that is to be updated or
retrieved for the given operation.
Example: Get the status of the spooler service
winrm get wmicimv2/Win32_Service?name=spooler -fragment:Status/text()
-options:{KEY=”VALUE“[;KEY=”VALUE“]}
Key/value pairs for provider-specific options.
Example:
-options:{key1=“value1”;key2=$null}
WinRM is the Microsoft implementation of WS-Management Protocol, a
standard Simple Object Access Protocol (SOAP)-based, firewall-friendly
protocol that allows hardware and operating systems, from different vendors,
to interoperate.
To improve security, WinRM 2.0 uses HTTP/HTTPS ports 5985/5986 by
default.
If the computer name is passed using r:<Computername> , then the
default client port will be used (by default, 5985/5986).
If the computer name is passed as a URI, such as r:http://Mycomputer/wsman,
then the IE default ports will be used (ports 80/443 by default).
Examples
Configure Windows Remote Management on the server (DemoServer2),
run this from an elevated CMD (or powershell) prompt:
C:\> winrm quickconfig
On a client you can then open a remote shell connected to DemoServer2
with:
winrs -r:DemoServer2 cmd
Retrieve current configuration in XML format:
winrm get winrm/config -format:pretty
Retrieve spooler instance of Win32_Service class:
winrm get wmicimv2/Win32_Service?Name=spooler
Modify a configuration property of WinRM:
winrm set winrm/config @{MaxEnvelopeSizekb=“100”}
Disable a listener on this machine:
winrm set winrm/config/Listener?Address=*+Transport=HTTPS
@{Enabled=“false”}
Create instance of HTTP Listener on IPv6 address:
winrm create winrm/config/Listener?
Address=IP:3ffe:8311:ffff:f2c1::5e61+Transport=HTTP
Delete the HTTP listener on this machine for given IP address:
winrm delete winrm/config/Listener?
Address=IP:192.168.2.1+Transport=HTTP
Call StartService method on Spooler service:
winrm invoke StartService wmicimv2/Win32_Service?Name=spooler
Call Create method of Win32_Process class with specified parameters:
winrm invoke Create wmicimv2/Win32_Process
@{CommandLine=“notepad.exe”;CurrentDirectory=“C:\”}
Display error message associated with the error code 0x5:
winrm helpmsg 0x5
WINRS
Windows Remote Shell
Syntax
winrs [-/SWITCH[:VALUE]] COMMAND
Key
COMMAND Any string that can be executed as a command in the cmd.exe shell.
(All switches accept both short form or long form. For example both -r and
-remote are valid.)
-r[emote]:ENDPOINT The target endpoint using a NetBIOS name or the standard
connection URL: [TRANSPORT://]TARGET[:PORT].
If not specified -r:localhost is used.
-un[encrypted] Messages to the remote shell will not be encrypted. This is useful for
troubleshooting, or when the network traffic is already encrypted using
ipsec, or when physical security is enforced.
By default the messages are encrypted using Kerberos or NTLM keys.
This switch is ignored when HTTPS transport is selected.
-u[sername]:USERNAME Username. If -username is specified, -password must be as well.
If not specified Winrs will negotiate authentication or prompt.
-p[assword]:PASSWORD Password. If not specified winrs will prompt for it.
-d[irectory]:PATH The starting directory for remote shell.
If not specified the remote shell will start in %USERPROFILE%.
-env[ironment]:STRING=VALUE
A single environment variable to be set when shell starts.
This allows changing default environment for the shell.
Multiple occurrences of this switch may be used.
-noe[cho] Disable echo. This may be necessary to ensure that user’s answers
to remote prompts are not displayed locally. By default echo is “on”.
-nop[rofile] Do not load the user’s profile. By default the server will attempt to load
the user profile. If the remote user is not a local administrator on the
target system then this option will be required.
-comp[ression] Turn on compression. Older installations on remote machines may
not support compression so it is off by default.
-[use]ssl Use an SSL connection when using a remote endpoint. Specifying this instead
of the transport “https:” will use the default WinRM default port.
-? Help
Note that you can’t open a full interactive remote powershell console,
but as remoting functionality is built-in to Powershell 2.0 there isn’t any need.
Connecting to the remote server ‘myserver’
winrs -r:https://myserver.com command
winrs -r:myserver.com -usessl command
winrs -r:myserver command
winrs -r:http://127.0.0.1 command
winrs -r:http://169.51.2.101:80 -unencrypted command
winrs -r:https://[::FFFF:129.144.52.38] command
winrs -r:http://[1080:0:0:0:8:800:200C:417A]:80 command
winrs -r:https://myserver.com -t:600 -u:administrator -p:$%fgh7 ipconfig
winrs -r:myserver -env:PATH=^%PATH^%;c:\tools -env:TEMP=d:\temp
config.cmd
winrs -r:myserver netdom join myserver /domain:testdomain /userd:johns
/passwordd:$%fgh789
WMIC.exe
Windows Management Instrumentation Command.
Read a huge range of information about local or remote computers. Also
provides a way to make configuration changes to multiple remote machines.
Syntax
Retrieve information about <Alias>:
WMIC [global_switches] [/locale:ms_409] <alias> [options] [format]
Interactive mode:
WMIC
Aliases:
ALIAS - Access local system aliases [CALL]
BASEBOARD - Base board management (motherboard or system board)
BIOS - BIOS management (Basic input/output services)
BOOTCONFIG - Boot configuration
CDROM - CD-ROM
COMPUTERSYSTEM - Computer system [CALL/SET]
CPU - CPU
CSPRODUCT - Computer system product information from SMBIOS.
DATAFILE - DataFiles [CALL]
DCOMAPP - DCOM Applications.
DESKTOP - User’s Desktop
DESKTOPMONITOR - Desktop Monitor
DEVICEMEMORYADDRESS - Device memory addresses
DISKDRIVE - Physical disk drive
DISKQUOTA - Disk space usage for NTFS volumes.[SET]
DMACHANNEL - Direct memory access (DMA) channel
ENVIRONMENT - System environment settings [SET]
FSDIR - Filesystem directory entry [CALL]
GROUP - Group account [CALL]
IDECONTROLLER - IDE Controller
IRQ - Interrupt request line
JOB - Jobs scheduled using the schedule service.[CALL]
LOADORDER - System services that define execution dependencies.
LOGICALDISK - Local storage devices [CALL/SET]
LOGON - LOGON Sessions.
MEMCACHE - Cache memory
MEMLOGICAL - System memory, layout and availability
MEMPHYSICAL - Physical memory management
NETCLIENT - Network Client management.
NETLOGIN - Network login information for a particular user.
NETPROTOCOL - Protocols (and their network characteristics).
NETUSE - Active network connection.
NIC - Network Interface Controller (NIC)
NICCONFIG - Network adapter. [CALL]
NTDOMAIN - NT Domain. [SET]
NTEVENT - NT Event Log.
NTEVENTLOG - NT eventlog file [CALL/SET]
ONBOARDDEVICE - Common adapter devices built into the motherboard.
OS - Operating System/s [CALL/SET]
PAGEFILE - Virtual memory file swapping
PAGEFILESET - Page file settings [SET]
PARTITION - Partitioned areas of a physical disk.
PORT - I/O ports
PORTCONNECTOR - Physical connection ports
PRINTER - Printer device [CALL/SET]
PRINTERCONFIG - Printer device configuration
PRINTJOB - Print job [CALL]
PROCESS - Processes [CALL]*
PRODUCT - Windows Installer [CALL]
QFE - Quick Fix Engineering (patches)
QUOTASETTING - Setting information for disk quotas on a volume. [SET]
REGISTRY - Computer system registry [SET]
SCSICONTROLLER - SCSI Controller [CALL]
SERVER - Server information
SERVICE - Service application [CALL]
SHARE - Shared resourcees [CALL]
SOFTWAREELEMENT - Elements of a software product*
SOFTWAREFEATURE - Subsets of SoftwareElement. [CALL]*
SOUNDDEV - Sound Devices
STARTUP - Commands that run automatically when users logon
SYSACCOUNT - System account
SYSDRIVER - System driver for a base service. [CALL]
SYSTEMENCLOSURE - Physical system enclosure
SYSTEMSLOT - Physical connection points including ports,
slots and peripherals, and proprietary connections points.
TAPEDRIVE - Tape drives
TEMPERATURE - Temperature sensor (electronic thermometer).
TIMEZONE - Time zone data
UPS - Uninterruptible power supply (UPS)
USERACCOUNT - User accounts [CALL/SET]
VOLTAGE - Voltage sensor (electronic voltmeter) data
VOLUME - Local storage volume [CALL/SET]
VOLUMEQUOTASETTING - Associates the disk quota setting with a specific disk volume.
[SET]
WMISET - WMI service operational parameters [SET]
New aliases in Windows 2003:
MEMORYCHIP - Memory chip information.
RDACCOUNT - Remote Desktop connection permission [CALL]
RDNIC - Remote Desktop connection on a specific network adapter [CALL/SET]
RDPERMISSIONS - Permissions to a specific Remote Desktop connection [CALL]
RDTOGGLE - Turn Remote Desktop listener on or off remotely[CALL]
RECOVEROS - Blue Screen Information [SET]
SHADOWCOPY - Shadow copy management [CALL]
SHADOWSTORAGE - Shadow copy storage areas [CALL/SET]
VOLUMEUSERQUOTA - Per user storage volume quotas [SET]
Options
By default an alias will return a standard LIST of information, you can
also choose to GET one or more specific properties.
Configuration changes can be made, where indicated above with: [CALL
or SET ]
The CREATE and DELETE options allow you to change the WMI
schema itself.
alias
alias LIST [BRIEF | FULL | INSTANCE | STATUS |SYSTEM | WRITEABLE]
[/TRANSLATE:BasicXml|NoComma ]
[/EVERY:no_secs] [/FORMAT:format]
alias GET [property list]
[/VALUE ] [/ALL ] [/TRANSLATE:BasicXml|NoComma ]
[/EVERY:no_secs] [/FORMAT:format]
alias CALL method_name [parameters]
alias SET [assignments]
alias CREATE
alias DELETE
alias ASSOC [/RESULTCLASS:classname] [/RESULTROLE:rolename]
[/ASSOCCLASS:assocclass]
For more help
WMIC /locale:ms_409 /alias /?
WMIC /locale:ms_409 /alias option /?
e.g.
WMIC /locale:ms_409 /BIOS /CALL /?
WMIC /locale:ms_409 /MEMLOGICAL /SET /?
All output files are unicode text (convert to ASCII with TYPE) Tab
Separated Values (.tsv) can be opened in excel
The PROCESS alias can be used to start a new installation process, if
doing this across the network, place the installer files on a share with
permissions EVERYONE : Read Only. This is because network credentials
will be dropped when jumping from one remote machine to another (unless
you have kerberos configured).
Examples
WMIC /locale:ms_409 OS
WMIC OS LIST BRIEF
WMIC OS GET csname, locale, bootdevice
WMIC OS GET osarchitecture /value
WMIC /locale:ms_409 NTEVENT where LogFile=‘system’
WMIC NTEVENT where “LogFile=‘system’ and Type>‘0’”
WMIC SERVICE where (state=”running”) GET caption, name, state > services.tsv
WMIC SERVICE where caption=‘TELNET’ CALL STARTSERVICE
WMIC PRINTER LIST STATUS
WMIC PRINTER where PortName=“LPT1:” GET PortName, Name, ShareName
WMIC /INTERACTIVE:ON PRINTER where PortName=“LPT1:” DELETE
WMIC PROCESS where name=‘evil.exe’ delete
WMIC /output:”%computername%.txt” MEMORYCHIP where “memorytype=17” get
Capacity
WMIC /node:@workstns.txt /failfast:on PROCESS call create “\server\share\installer.cmd”
Interactive mode:
C:>START “Windows Management” WMIC
wmic:root\cli>/locale:ms_409
wmic:root\cli>OS get csname
wmic:root\cli>quit
Notes
WMIC is available on XP Professional and Windows 2003 or later
versions of Windows.
The availability of WMI information does vary across different versions
of Windows
e.g. ODBC, SNMP, Windows Installer.
To run WMIC requires administrator rights.
In Windows 2000, around 4,000 properties can be monitored, and around
40 can be configured.
In Windows XP around 6,000 properties can be monitored, and around 140
can be configured.
Windows 2003 offers a few improvements and bug fixes: the global
option /locale:ms_409 is not required (it defaults to English US.)
When you type WMIC for the first time in Windows 2003 all the aliases
are compiled. The second, and subsequent times you run WMIC, it will start
immediately. Under XP WMIC is slower to initialise, therefore to run several
WMI queries it can be quicker to use interactive mode.
* WMI information for installed software packages (PACKAGE and
SOFTWAREFEATURE) is often incomplete and inconsistent for a variety of
historical reasons. A more reliable method is to retrieve a list of installed
programs directly from the Add/Remove list in the registry, with a WSH
script like this from Torgeir Bakken.
WUAUCLT
Windows Update Agent, download new Windows Update files.
Syntax
wuauclt Options
Options:
/a or /ResetAuthorization Initiate an asynchronous background search for applicable updates.
If Automatic Updates are disabled, this has no effect.
/r or /ReportNow Send all queued reporting events to the server asynchronously.
/DetectNow Initiate detection right away, Query the WSUS server immediately
to see if any new updates are needed.
XCACLS.exe (*)
Display or modify Access Control Lists (ACLs) for files and folders.
Syntax
XCACLS filename [options]
XCACLS filename
Key
If no options are specified XCACLS will display the ACLs for the file(s)
options can be any combination of:
/T Traverse all subfolders and change all matching files found.
/E Edit ACL instead of replacing it.
/x Edit ACL instead of replacing it; affect only ACEs that this user already owns*
/R user Revoke all access rights from the given user.
/D user Deny specified user access, this will over-ride
all other permissions the user has.
/C Continue on access denied errors.
/Y Replace user’s rights without verify
/P user:permision[;FolderSpec]
Replace user’s rights. see /G option below
/G user:permision[;FolderSpec]
Grant specified user access rights, permision can be:
r Read
c Change (write)
f Full control
p Change Permissions (Special access)
o Take Ownership (Special access)
x EXecute (Special access)
e REad (Special access)
w Write (Special access)
d Delete (Special access)
t Used only by FolderSpec. see below
* Option only valid in Windows 2003
FolderSpec = ;T@ where @ is one of the rights above, when this is specified
new files will inherit FolderSpec instead of permission. At least one folder
access right must follow the T For example ;TF will apply full control (but
;FT is not valid)
Wildcards can be used to specify more that one file in a command. You can
specify more than one user in a command. You can combine access rights.
Although taking ownership is listed as an option it does not work, use
SUBINACL for this.
Inheritance Errors
“Permissions incorrectly ordered” - the quickest way to resolve or avoid
these errors is to use the newer iCACLS command instead of XCACLS.
Inherited folder permissions are displayed as:
OI - Object inherit - This folder and files. (no inheritance to subfolders)
CI - Container inherit - This folder and subfolders.
IO - Inherit only - The ACE does not apply to the current file/directory
These can be combined as folllows:
:: Allow guests the Full Control permission in MyFolder and all subfolders
XCACLS MyFolder /T /E /G guests:f
:: Grant guests only read access to all files in and below MyFolder,
:: new folders created will be Read Access only, new files will not inherit any
rights.
XCACLS MyFolder /T /P guests:R;Tr
:: Grant guests only execute access to all files in and below MyFolder
XCACLS MyFolder /T /P guests:x
XCOPY
Copy files and/or directory trees to another folder. XCOPY is similar to
the COPY command except that it has additional switches to specify both the
source and destination in detail.
NOTE: Xcopy is now deprecated under Vista and Windows 2008 - use
Robocopy instead
[options] can be any combination of the following:
Source Options
/A Copy files with the archive attribute set (default=Y)
/M Copy files with the archive attribute set and
turn off the archive attribute, use this option
when making regular Backups (default=Y)
/H Copy hidden and system files and folders (default=N)
/D:mm-dd-yyyy
Copy files changed on or after the specified date.
If no date is given, copy only files whose
source date/time is newer than the destination time.
/U Copy only files that already exist in destination.
/S Copy folders and subfolders
/E Copy folders and subfolders, including Empty folders.
May be used to modify /T.
/EXCLUDE:file1[+file2][+file3]…
(Windows 2000 only) The files can each contain one
or more full or partial pathnames to be excluded.
When any of these match any part of the absolute path
of a SOURCE file, then that file will be excluded.
For example, specifying a string like \obj\ or .obj will exclude
all files underneath the directory obj or all files with the
.obj extension respectively.
Copy Options
/W Prompt you to press a key before starting to copy.
/P Prompt before creating each file.
/Y (Windows 2000 only) Suppress prompt to confirm overwriting a file.
may be preset in the COPYCMD env variable.
/-Y (Windows 2000 only) Prompt to confirm overwriting a file.
/V Verify that the new files were written correctly.
/C Continue copying even if an error occurs.
/I If in doubt always assume the destination is a folder
e.g. when the destination does not exist.
/Z Copy files in restorable mode. If the copy is interrupted part
way through, it will restart if possible. (use on slow networks)
/Q Do not display file names while copying.
/F Display full source and destination file names while copying.
/L List only - Display files that would be copied.
Destination Options
/R Overwrite read-only files.
/T Create folder structure, but do not copy files. Do not
include empty folders or subfolders.
/T /E will include empty folders and subfolders.
/K Copy attributes. XCOPY will otherwise reset read-only attributes.
/N If at all possible, use only a short filename (8.3) when creating
a destination file. This may be necessary when copying between disks
that are formatted differently e.g NTFS and VFAT, or when archiving
data to an ISO9660 CDROM.
/O (Windows 2000 only) copy file Ownership and ACL information.
/X Copy file audit settings (implies /O).
Examples:
To copy a file:
To copy a folder:
Notes
REM
In a batch file REM at the start of a line signifies a comment or
REMARK
alternatively adding :: at the start of a line has a similar effect
For example:
@ECHO OFF
::
:: First comment
::
REM Second comment
REM
::
Although you can use rem without a comment to add vertical spacing to a
batch file, you can also use completely blank lines. The blank lines are
ignored when processing the batch program.
The double-colon is not documented as a comment command, it is a
special case of a CALL label that acts like a comment. The pro’s and cons of
each method are listed below.
Bugs
There are problems using a :: comment within an IF or FOR code bracket
e.g.
@echo off
FOR /L %%i IN (1,1,10) Do (
Echo before comment
:: Some comment
Echo after comment
)
The above will return the error :: was unexpected at this time.
In Windows 2000 and XP a comment like
::%~
or
REM %~ will be interpreted giving the error:
The following usage of the path operator in batch-parameter substitution is
invalid: %~
In Windows NT 4 the REM command would incorrectly reset the
%errorlevel% to 0
The bottom line on this is that you must test your comments to be sure
they will be ignored as you expect.
Registry Comments
FTP Comments
There is no valid comment character for FTP but you can cheat by
escaping to the shell and running REM
e.g.
C:\WORK>type ftpscript
!REM This is a remark
bye
C:\WORK>ftp -s:ftpscript
ftp> !REM This is a remark
ftp> bye
C:\WORK>
ADDUSERS Add or list users to/from a CSV file
GETMAC Display the Media Access Control (MAC)
address
IPCONFIG Configure IP
RD Delete folder(s)•
SC Service Control
SU Switch User
:: Comment / Remark•
Commands marked • are Internal commands only available within the
CMD shell.
All other commands (not marked with •) are external commands.
External commands may be used under the CMD shell, PowerShell, or
directly from START-RUN.
Using the “Windows Key”
A quick reference to what you can get out of the Windows key
(also known as the Windows key, the home key, the meta key, the start
key, MOD4, or the flag key (sometimes shortened to flag)
Yes…that key actually does something…
Tapping the Windows key without pressing any other keys toggles the
Start Menu. Ctr l + Es c duplicates this functionality, but cannot be used in
place of the Windows key in other shortcuts.
As of Windows XP
Wi n + B to select the first icon in the Notification Area.
Wi n + D to show the desktop, or restore hidden programs when
pressed a second time.
Wi n + E to open Windows Explorer.
Wi n + F to open Windows Search.
Wi n + CTR L + F to open Search for Computers. Requires Active
Directory Domain Services.
Wi n + CTR L + AL T +↵ Enter toggles full screen in Microsoft
Internet Explorer. This shortcut has been discontinued, replaced by
F1 1 .
Wi n + F 1 to open Windows Help.
Wi n + L to lock the desktop or switch users.
Wi n + M to minimize all windows.
Wi n +⇧ Shift + M to restore windows that were minimized with
Wi n + M .
Wi n + R to open the Run dialog.
Wi n + U to run the Utility Manager, known as Ease of Access in
later versions of Windows.[4]
Wi n + Paus e or Wi n + Brea k to open System Properties.
Start | Run
The Win + R combination opens the Run dialog.
Run Command List
(Compatible with Windows XP, Windows Vista, Windows 7 and
Windows 10)
Option Run
Command
Calculator calc
Findfast findfast.cpl
HyperTerminal hypertrm
Netmeeting conf
Notepad notepad
Paint pbrush
Services services.msc
Wordpad write
POWERSHELL COMMAND
TRANSLATION
Find all *.txt files dir /s *.txt get-childitem -recurse -include *.txt
alias: dir -r -i *.txt
Find all *.txt files findstr “foo” *.txt dir *.txt | select-string “foo”
containing a particular
string
PowerShell commands that allow you to do what the GUI finds difficult.
Operation PowerShell
Set the current directory to a UNC
cd \\myserver\\myshare
path
cd hkcu:
Treat the registry like a filesystem
dir
$f = Get-Content “myfile.txt”
Count the results of a directory
foreach ($item in $f)
listing
{do stuff with $item}
Microsoft’s list of Powershell commands:
Clear-Recyclebin
Configuration
Convert-String
ConvertFrom-SddlString
Disable-PSTrace
Disable-PSWSManCombinedTrace
Disable-WSManTrace
Enable-PSTrace
Enable-PSWSManCombinedTrace
Enable-WSManTrace
Export-BinaryMiLog
Format-Hex
Get-FileHash
Get-IseSnippet
Get-Item Gets the item at the specified
location.
Get-LogProperties
Get-NetworkSwitchFeature
Get-PSHostProcessInfo
Get-PSProvider Gets information about the
specified Windows PowerShell
provider.
Import-BinaryMiLog
Import-IseSnippet
Import-PowerShellDataFile
New-Guid
New-IseSnippet
Register-ArgumentCompleter
Set-LogProperties
Start-Trace
Stop-Trace
C:\WINDOWS\SYSTEM32> exit