0% found this document useful (0 votes)
253 views460 pages

CMD Computer Depth Programming

Uploaded by

Kubilay Doğan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
253 views460 pages

CMD Computer Depth Programming

Uploaded by

Kubilay Doğan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 460

©

2018 WordMean Publishing



Every effort has been made to ensure that this publication contains
accurate and current information at the time of its publication however; the
publisher and the author(s) shall not be liable for any loss, damage or liability
as a result of the information contained herein.

All trademarks mentioned within the published works are acknowledged
as belonging to their respected owners.
This work is creator endorsed under a strict set of guidelines aiming for a
non-capitalist publishing ideology and therefore all fairness between
publisher and author(s) has been insured under the hope that these guides are
respected by the consumer of such works.

Although the author and publisher have made every effort to ensure that
the information in this book was correct at press time, the author and
publisher do not assume and hereby disclaim any liability to any party for any
loss, damage, or disruption caused by errors or omissions, whether such errors
or omissions result from negligence, accident, or any other cause.


CMD Your Contents
DEFINITION: COMMAND
Internal commands
Batch file commands
Variables
Redirection, piping, and chaining
Limitations
Interesting…
DOS
Your History Lesson for Today!
SYSTEM FILE CHECKER (SFC):
CHECK DISK
IPCONFIG
DRIVERQUERY
ACALC
APPEND
ASSIGN
ATTRIB
BACKUP
IBM BASICBASIC, BASICA and GW-BASIC
BREAK
CALL
CHCP
CHDIR or CD
CHKDSK
CHOICE
CLS
COMMAND.COM COMMAND
COMP
COPY
CTTY
DATE
DEBUG
DEFRAG
DEL or ERASE
DELTREE
DIR
DISKCOMP
DISKCOPY
DOSKEY
DRVLOCK
DYNALOAD
E
ECHO
MS-DOS Editor EDIT
EDLIN
EJECT
EMM386
EXE2BIN
EXIT
FASTOPEN
FC
FDISK
FIND
FOR
FORMAT
GOTO
GRAFTABL
GRAPHICS
HELP
IF
INTERLNK
INTERSVR
JOIN
KEYB
LABEL
LOADFIX
LOADHIGH or LH
MEM
MIRROR
MKDIR or MD
MODE
MORE
MOVE
MSCDEX
MSD
NLSFUNC
PATH
PAUSE
POWER
PRINT
PROMPT
QBASIC
QCONFIG
RECOVER
REM
RENAME or REN
REPLACE
RESTORE
REXX
REXXDUMP
RMDIR or RD
SCANDISK
SET
SETVER
SHARE
SHIFT
Smartdrive (SMARTDRV)
SORT
SUBST
SYS
TIME
TREE
TRUENAME
type (command)TYPE
UNDELETE
UNFORMAT
VER
VERIFY
VOL
XCOPY
START (COMMAND)
Command Syntax
TITLE (COMMAND)
Syntax
Example
TYPE
FOLDERS AND DIRECTORY TREES
Interesting…
How the FOLDER became the FOLDER
ECHO (COMMAND)
Usage example
Implementation example
DATE
DEFRAG
DEL
DELPROF (*)
DIR
DIRUSE (2K RESOURCE KIT / XP SUPPORT TOOLS)
DISKCOMP.COM
DISKCOPY.COM
DISKPART (WINDOWS 7)
DOSKEY.EXE
DSACLS.EXE
ECHO
ENDLOCAL
EVENTCREATE (WINDOWS 2003/2008)
EXIT
EXPAND
EXPAND
FC.EXE
FIND
FINDSTR
FOR /F
FOR /F
FOR
FORFILES.EXE (*)
FORMAT.COM
FSUTIL.EXE
FTP
FTYPE
GLOBAL (*)
GOTO
GPUPDATE.EXE
HELP
ICACLS.EXE (2003 SP2, VISTA)
IF
IFMEMBER (*)
IPCONFIG
LABEL
LOCAL (*)
LOGEVENT (*)
LOGMAN.EXE
LOGTIME.EXE (*)
LOGOFF.EXE (*)
MAPISEND (BACK OFFICE/EXCHANGE RESOURCE KIT)
MBSACLI
MEM
MD
MKLINK (VISTA) OR LINKD (*)
MODE
MORE
MOUNTVOL (WINDOWS 2000/2003/SERVER 2008)
MOVEUSER.EXE (*)
MSG.EXE
MSIEXEC
MSINFO32.EXE
MSTSC
NET.EXE
NETDOM.EXE (WINDOWS SERVER 2003/2008)
NETSH (NETWORK SHELL)
NBTSTAT.EXE
NETSTAT.EXE
NOW.EXE (*)
NTBACKUP
NSLOOKUP (TCP/IP)
NTRIGHTS.EXE (RESOURCE KIT, 2000/2003)
OPENFILES.EXE
PERMS.EXE (WINDOWS 2000)
PAUSE
TYPEPERF.EXE
PING
POPD
POWERCFG (VISTA/WINDOWS7/SERVER 2008)
PRINT
PRINTBRM.EXE
PRNCNFG.VBS (XP AND .NET)
PRNMNGR (XP AND ABOVE)
PROMPT
PSEXEC (PART OF PSTOOLS – PLEASE NOTE YOU HAVE TO DOWNLOAD
PSEXEC FROM MICROSOFT SITE)
PSFILE (PART OF PSTOOLS – ALSO MUST BE ACQUIRED FROM MICROSOFT
SITE)
PATHPING
RASDIAL (DIAL UP NETWORKING)
RASPHONE (DIAL UP NETWORKING)
RECOVER
REG.EXE
REGEDIT
REGSVR32
REGINI (*)
REM
REN
REPLACE
RD
ROBOCOPY.EXE (XP RESOURCE KIT/STANDARD WINDOWS 7 COMMAND)
ROBOCOPY.EXE (XP RESOURCE KIT/STANDARD WINDOWS 7 COMMAND)
ROUTE.EXE
RUNAS
RUNDLL32.EXE
SC.EXE (*)
SCHTASKS
SCLIST (*)
SET
SETLOCAL
SETX.EXE (RESOURCE KIT, WINDOWS 7)
SFC (WINDOWS XP, SERVER 2003, WIN 7)
SHARE.VBS (*)
SHORTCUT.EXE (NT SERVER RESOURCE KIT)
SHOWGRPS (*)
SHOWMBRS (*)
HUTDOWN.EXE (FOR TERMINAL SERVICES USE: TSSHUTDN)
SLEEP.EXE (*)
SLMGR.VBS (WINDOWS7/2008)
SOON.EXE (*)
SORT
START
SU (*)
SUBINACL.EXE (*)
SUBST
SYSTEMINFO
TASKLIST
TASKLIST
TIME
TIMEOUT.EXE (*)
TITLE
TLIST (RESOURCE KIT & WINDOWS 2000 SUPPORT TOOLS)
TOUCH (WINDOWS 2000 RESOURCE KIT)
TRACERT
TSSHUTDN
TYPE
TYPEPERF.EXE
VER
VERIFY
VOL
WAITFOR.EXE (2003 RESOURCE KIT, STANDARD IN WINDOWS 7/2008)
WHERE (2K RESOURCE KIT / WINDOWS 2003)
WHOAMI.EXE (*)
WINDIFF (WINDOWS SDK)
WINMSDP.EXE (*)
WINRM
WINRS
WMIC.EXE
WUAUCLT
XCACLS.EXE (*)
XCOPY
REM
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)
START | RUN
POWERSHELL QUICK COMMANDS


INTRODUCTION
This book covers commands that are compatible with MS-DOS 6
all the way through to Windows 10.

The guides within refer to Windows 2000, XP, Vista, 7, 8, 8.1 and
Windows 10 as “21st Century Windows”

The basic commands will be detailed briefly within the first few
chapters and followed in-depth later in the book.


DEFINITION: Command
In computing, a command is a directive to a computer program acting as an
interpreter of some kind, in order to perform a specific task. Most commonly a
command is a directive to some kind of command line interface, such as a
shell.


Internal commands
All commands are run only after the Enter key is pressed at the end of the
line. COMMAND.COM is not case-sensitive, meaning commands can be
typed in either case and are all equivalent.
BREAK
Controls the handling of program interruption with Ctrl+C or Ctrl+Break.
CHCP
Displays or changes the current system code page.
CHDIR, CD
Changes the current working directory or displays the current directory.
CLS
Clears the screen.
COPY
Copies one file to another (if the destination file already exists, MS-DOS asks whether to
replace it). (See also XCOPY, an external command that could also copy directory trees).
CTTY
Defines the device to use for input and output.
DATE
Display and set the date of the system.
DEL, ERASE
Deletes a file. When used on a directory, deletes all files.
DIR
Lists the files in the specified directory.
ECHO
Toggles whether text is displayed (ECHO ON) or not (ECHO OFF). Also displays text on
the screen (ECHO text).
EXIT
Exits from COMMAND.COM and returns to the program which launched it.
LFNFOR
Enables or disables the return of long filenames by the FOR command. (Windows 95/98/Me
only).
LOADHIGH, LH
Loads a program into upper memory (HILOAD in DR DOS).
LOCK
Enables external programs to perform low-level disk access to a volume. (Windows
95/98/Me only).
MKDIR, MD
Creates a new directory.
PATH
Displays or changes the value of the PATH environment variable which controls the places
where COMMAND.COM will search for executable files.
PROMPT
Displays or change the value of the PROMPT environment variable which controls the
appearance of the prompt.
REN, RENAME
Renames a file or directory.
RMDIR, RD
Removes an empty directory.
SET
Sets the value of an environment variable ; Without arguments, shows all defined
environment variables.
TIME
Display and set the time of the system.
TRUENAME
Display the fully expanded physical name of a file, resolving ASSIGN, JOIN and SUBST
logical filesystem mappings.
TYPE
Display the content of a file on the console.
UNLOCK
Disables low-level disk access. (Windows 95/98/Me only)
VER
Displays the version of the operating system.
VERIFY
Enable or disable verification of writing for files.
VOL
Shows information about a volume.


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.

Redirection, piping, and chaining


Because DOS is a single-tasking operating system, piping is achieved by
running commands sequentially, redirecting to and from a temporary file.
COMMAND.COM makes no provision for redirecting the standard error
channel.
command < filename
Redirect standard input from a file or device
command > filename
Redirect standard output, overwriting target file if it exists.
command >> filename
Redirect standard output, appending to target file if it exists.
command1 | command2
Pipe standard output from command1 to standard input of command2
command1 & command2
Commands separated by & are executed in sequence (=chaining of commands). In other
words: first command1 is executed until termination, then command2.

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.

Your History Lesson for Today!


IBM PC-DOS (and the separately sold
MS-DOS) and its predecessor, 86-DOS,
were loosely inspired by Digital
Research’s CP/M, which was the
dominant disk operating system for 8-
bit Intel 8080 and Zilog Z80 based
microcomputers. PC-DOS ran on Intel
80x86-family processors.
When IBM introduced the IBM PC,
built with the Intel 8088
microprocessor, they needed an
operating system. Seeking an 8088-
compatible build of CP/M, IBM
initially approached Microsoft CEO Bill Gates (possibly believing that
Microsoft owned CP/M due to the Microsoft Z-80 SoftCard, which allowed
CP/M to run on an Apple II). IBM was sent to Digital Research, and a
meeting was set up. However, the initial negotiations for the use of CP/M
broke down—Digital Research wished to sell CP/M on a royalty basis, while
IBM sought a single license, and to change the name to “PC DOS”. DR
founder Gary Kildall refused, and IBM withdrew.

IBM again approached Bill Gates. Gates in turn approached Seattle Computer
Products. There, programmer Tim Paterson had developed a variant of CP/M-
80, intended as an internal product for testing SCP’s new 16-bit Intel 8086
CPU card for the S-100 bus. The system was initially named “QDOS” (Quick
and Dirty Operating System), before being made commercially available as
86-DOS. Microsoft purchased 86-DOS, allegedly for $50,000. This became
Microsoft Disk Operating System, MS-DOS, introduced in 1981.

Microsoft also licensed their system to multiple computer companies, who
supplied MS-DOS for their own hardware, sometimes under their own names.
Microsoft later required the use of the MS-DOS name, with the exception of
the IBM variant. IBM continued to develop their version, PC DOS, for the
IBM PC. Digital Research became aware that an operating system similar to
CP/M was being sold by IBM (under the same name that IBM insisted upon
for CP/M), and threatened legal action. IBM responded by offering an
agreement: they would give PC consumers a choice of PC DOS or CP/M-86,
Kildall’s 8086 version. Side-by-side, CP/M cost almost $200 more than PC
DOS, and sales were low. CP/M faded, with MS-DOS and PC DOS becoming
the marketed operating system for PCs and PC compatibles.

Microsoft originally only sold MS-DOS to Original equipment manufacturers
(OEMs). One major reason for this was that not all early PCs were 100% IBM
PC compatible. DOS was structured such that there was a separation between
the system specific device driver code (IO.SYS) and the DOS kernel
(MSDOS.SYS). Microsoft provided an OEM Adaptation Kit which allowed
OEMs to customize the device driver code to their particular system. By the
early 1990s, most PCs adhered to IBM PC standards so Microsoft began
selling MS-DOS in retail with MS-DOS 5.0.

NOTE: Many of these tools require that you run the Command Prompt with
administrator privileges. To do that, right-click the Command Prompt icon
and choose Run as administrator. Better yet, pin it to your Start menu or
taskbar, right-click it and choose Properties, click the Advanced button, and
choose Run as administrator. That way, it will run with elevated privileges
every time.

SYSTEM FILE CHECKER (SFC):


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.

IBM BASICBASIC, BASICA and GW-BASIC


External - DOS 1.0 to DOS 4.0
An implementation of the BASIC programming language for PCs.
IBM computers had Cassette BASIC in ROM; BASIC (Disk BASIC) and BASICA
(Advanced BASIC) were extensions to the ROM-based Cassette BASIC.
Microsoft released GW-BASIC for IBM compatible PCs which did not have ROM BASIC.
GW-BASIC was a complete BASIC interpreter which was compatible with BASICA. Some OEM
releases had BASIC.COM and BASICA.COM as loaders for GW-BASIC.EXE. MS-DOS 5.0 and
higher included QBasic instead of GW-BASIC.

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.

CHKDSK originated as an external command in 86-DOS.


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.

/O and /Y are only available in DOS 6 and above. /H is only available in


PC DOS 7.
COMMAND.COM originated in 86-DOS.

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).

/Y and /-Y are only available in DOS 6 and above.


COPY originated as an internal command in 86-DOS.

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.

DEBUG originated as an external command in 86-DOS.



DEFRAG
External - DOS 6.0 and above
Further information: Defragmentation
Reorganizes files on disks to optimize performance.
DEFRAG [drive:] [/F] [/Sorder] [/B] [/SKIPHIGH] [/LCD | /BW | /G0]DEFRAG [drive:]
[/U] [/B] [/SKIPHIGH] [/LCD | /BW | /G0] [drive:] Drive letter of disk to be optimized.
/F Fully optimizes specified disk. /U Unfragments files, leaving space between
files. /S Sort files by specified order. order N By Name (alphabetic) E
By extension (alphabetic) D By date & time (earliest first) S By size (smallest
first) - Suffix to reverse order /B Restarts your computer after optimization.
/SKIPHIGH Prevents Defrag from using extended or upper memory. /LCD Runs
Defrag using an LCD color scheme. /BW Runs Defrag using a black and white color
scheme. /G0 Disable the graphic mouse and graphic character set.

DEFRAG is a licensed version Norton Utilities Speed Disk.


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.

/P is only available in DOS 5 and above.


ERASE (but not its alias DEL) originated as an internal command in 86-DOS.
All versions of DR-DOS support the ERA command as an alias to ERASE /
DEL and add ERAQ / DELQ shortcuts identical to the DR-DOS ERA /
ERASE / DEL command with the /Q (Query) option given to prompt the user
for confirmation.

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.

Only /P and /W are available prior to DOS 5.


DIR originated as an internal command in 86-DOS.

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.

DRVLOCK is only included with PC DOS versions.


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.

MS-DOS Editor EDIT


External - MS-DOS 5.0 and above
Starts the MS-DOS editor, which creates and changes ASCII files.
EDIT [[drive:][path]filename] [/B] [/G] [/H] [/NOHI] [drive:][path]filename Specifies
the ASCII file to edit. /B Allows use of a monochrome monitor with a color
graphics card. /G Provides the fastest update of a CGA screen. /H Displays
the maximum number of lines possible for your hardware. /NOHI Allows the use of a
monitor without high-intensity support.

PC DOS 6.1 and later use the E editor.


EDLIN
External - DOS 1.0 and above
Line-oriented text editor.
EDLIN [drive:][path]filename [/B] /B Ignores end-of-file (CTRL+Z) characters.

EDLIN originated as an external command in 86-DOS.


EJECT
External - PC DOS 5.02 and above
Ejects the media from a drive.
EJECT [drive:]

EJECT is only included with PC DOS versions.


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.

EMM386.EXE must be loaded as a device driver in CONFIG.SYS in order to


use this command.

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.

/S is only available in PC DOS 7. Also PC DOS 7 allows the use of wildcards


in filenames while prior versions do not.

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.

This command uses the file GRAPHICS.PRO which contains information


about the supported printer types.

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.

INTERLNK.EXE must be loaded as a device driver in CONFIG.SYS in order


to use this command.

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.

KEYB replaces the commands KEYBFR, KEYBGR, KEYBIT, KEYBSP and


KEYBUK from DOS 3.0 to 3.2.

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.

/L is only available in DOS 6 and above.


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.

MIRROR is licensed from Central Point Software PC Tools


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.

MSD is only included with MS-DOS versions, PC DOS uses QCONFIG.


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

PAUSE originated as an internal command in 86-DOS.


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.

POWER.EXE must be loaded as a device driver in CONFIG.SYS in order to


use this command.

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.

QBASIC replaces GW-BASIC from earlier versions of DOS.


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.

Scandisk is only included with MS-DOS versions.


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.

SETVER.EXE must be loaded as a device driver in CONFIG.SYS in order to


use this command. While the internal version setting functionality was present
in DOS 4, the SETVER command did not appear until DOS 5.

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.

/NOHMA is only available in PC DOS 7.


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.

SYS originated as an external command in 86-DOS.


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

This command was undocumented in DOS 3.x.


type (command)TYPE
Internal - DOS 1.0 and above
Displays the contents of a text file.
TYPE [drive:][path]filename

TYPE originated as an internal command in 86-DOS.


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.

UNDELETE is licensed from Central Point Software PC Tools



UNFORMAT
External - DOS 5.0 and above
Restores a disk erased by the FORMAT command.
UNFORMAT drive: [/J]UNFORMAT drive: [/U] [/L] [/TEST] [/P]UNFORMAT /PARTN
[/L] drive: Specifies the drive to unformat. /J Verifies that the mirror files agree with
the system information on the disk. /U Unformats without using MIRROR
files. /L Lists all file and directory names found, or, when used with the
/PARTN switch, displays current partition tables. /TEST Displays information but does
not write changes to disk. /P Sends output messages to printer connected to LPT1.
/PARTN Restores disk partition tables.

UNFORMAT is licensed from Central Point Software PC Tools


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

/Y and /-Y are only available in DOS 6 and above.


Renaming the XCOPY program file to MCOPY under MS-DOS 3.2, the
command will no longer ask for confirmation if the target was meant as file or
directory. Instead, it will then automatically assume the target to be an
directory, if the source was given as a directory or as multiple files or was
ending on “\”.

• A Collection of Undocumented and Obscure Features in Various MS-
DOS Versions


Start (command)
The command start is used to start programs or batch files from in the
Windows Command Prompt, or to open files or directories using the default
program. The corresponding Mac command is open.

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.



Folders and Directory Trees


In computing, a directory, also referred to as a folder (especially in
Microsoft Windows), catalog (used in the Commodore 128 as a BASIC verb
for displaying directory contents), or drawer, is a virtual container within a
digital file system, in which groups of computer files and possibly other
directories can be kept and organized. The technically correct name for such a
file cataloging structure is directory, although names such as folder and
drawer were adopted to provide some relevancy to the traditional office file
cabinet.
Files are kept organized by storing related files in the same directory. In a
hierarchical filesystem (that is, one in which files and directories are
organized in a manner that resembles an inverted tree), a directory contained
inside another directory is called a subdirectory. The terms parent and child
are often used to describe the relationship between a subdirectory and the
directory in which it is cataloged, the latter being the parent. The top-most
directory in such a filesystem, which does not have a parent of its own, is
called the root directory.






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;
}

Perl can also emulate echo quite simply:


<?php #!/usr/bin/env perl
print join ” “, @ARGV ?>






Commands

For Windows Environments


Using CMD.exe









For the sake of quick refresh lets go over accessing Command Prompt:

Firstly, there are many ways to access CMD (Command Prompt)
CTRL+ALT+Z can be used
Windows key + R will open run, and allow you to launch CMD.exe
Or quite simply search for “command prompt”

Starting from the beginning with simple commands



Power deleting with the expanded “Del” command
The delete command “del” now has a switch “/s” that provides for deletions in subfolders. Thus
the commanddel /s myfolder\* will delete all files in myfolder and all files in any subfolders of
myfolder. Note the convenient asterisk wildcard “*”, which allows for multiple deletions in a single user
operation. Together with the switch “/s”, a single “del” command can clean out Temp folders and do
other useful housekeeping chores. Another switch “/f” will force the deletion of read-only files. If you
are sure about what is being deleted, add the “/q” switch to run in quiet mode so you aren’t asked if you
really want to delete for every single file. Because of its power, this extended del command has to be
used carefully. Any files deleted this way do not go into the Recycle Bin but are permanently removed.
To delete only files with a particular extension EXT, use the commanddel /s myfolder\*.ext Note
that this command will delete all files of a particular type in a folder and all its subfolders. One example
of its use is to get rid of all temporary files with the extension TMP.

Enhanced management of folders (directories)


The command “rmdir” or its twin “rd” are also expanded compared to the old DOS version. To
remove folders (directories), use “rmdir” (just “rd” will also work). Folders must be empty before they
can be deleted. However, there is a switch “/s” for deleting subfolders and with this switch files are also
deleted. It is like the old command “deltree”. The command rd /s myfolder will remove “myfolder” and
everything in it. Adding the switch /q for a “quiet” mode is also possible.
Options have also been added to the command for making folders. The command “mkdir” or
“md” can now make a whole tree. For example, consider the commandmd new\new1\new2 This will
create a folder “new” with a subfolder “new1” that in turn has a subfolder “new2”.

Xcopy- Powerful and versatile way to copy or back up files


For copying large numbers of files or backing up a large folder, the command line is often the
fastest and easiest way to go. The command “xcopy” is a very useful and powerful command for this
purpose. (The old DOS also had an “xcopy” command but it sometimes had trouble with long file
names. The XP version has no such problems.) “xcopy” comes with an alphabet soup of assorted
switches that give it great versatility for use as a file backup utility. Enter “xcopy /?” in a command
prompt to see them all. For example with the switch “/d:[mm-dd-yyy]” only files changed after a given
date are copied. A command that will copy all files from the folder myfolder that have changed since
June 1, 2003 to the folder mybackup is given byxcopy myfolder mybackup /d:06-01-2003 If no date is
specified the switch “/d” will copy all files that have changed at any time.As is true in general, if there
are spaces in a name, the path and file name have to be enclosed in quotes. Adding the switch “/s”
provides that subfolders and their contents will also be copied. Other switches provide for read-only and
hidden files. Altogether, there are something like 27 command line options for xcopy.



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.

Renaming files with “ren”


Renaming a a large number of files can be tedious. The command ren (also written rename) is
somewhat limited but its ability to use wild cards can sometimes be useful. The basic command is ren
file1 file2 The renamed file has to stay in the same folder as the original; this command cannot move
files to another folder. The wildcard capability can be used to change the extension of all files of a
certain type. Thus ren *.txt *.doc will rename all text files to have a DOC extension.

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”.

Changing file attributes with “attrib”


In addition to their actual content, files also have a set of properties that characterize them
(sometimes called metadata.) One set of these properties are the four attributes read-only, hidden,
system, and archive. The archive attribute is primarily used in backup procedures but the other three can
be encountered in various contexts. These attributes can be turned on or off with the command “attrib”
and its switches. The great utility of this command is that it can act on subfolders with its switch “/s”
and can use the wildcard “*”. For example, to clear the read-only , system, and hidden attributes from a
file use attrib -r -s -h somefile This operation is not uncommon when system files have to be edited. To
restore the attributes the command is attrib +r +s +h somefile A common situation where it is desirable
to clear the read-only attribute from many files is when files are copied from a CD. By default CD files
are normally marked read-only. This can interfere with editing. To clear the read-only attribute from all
files in a folder and its subfolders use attrib -r somefolder\*.* /s If you want to process all files of a
certain type such as MP3, use attrib -r somefolder\*.mp3 /s

How to make your favorite folder easily accessible in Windows dialog


boxes
Another older command that I find handy is “subst”. There are certain folders that I use over and
over and I like to have ready access to them. One way to do this is to use the command “subst” to assign
a drive letter to a folder. Since drives are at the top of My Computer and any folder trees in browse
lists, it makes the folder very easy to get to. To map the “Z:” drive to a folder “myfolder”, entersubst z:
myfolder Unless you are working from the parent folder of “myfolder” you will need the full path for it.
The assignment only lasts until the user logs off or the computer is shut down so I have a one-line batch
file in my Startup folder that reinstitutes the assignment.


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•

Commands marked • are Internal commands only available within the


CMD shell.
All other commands (not marked with •) are external commands which may
be used under the CMD shell, PowerShell, or directly from START-RUN.





















Please note = name of commands with (*) may require Microsoft
Sysinternals software in later Operating Systems such as Windows XP,
Windows Vista, Win7 and Win8











ADDUSER:

Syntax

Create Users:
AddUsers /c filename [/s:x] [/?] Domain Password_options
Dump to file:
AddUsers /d{:u} filename [/s:x] [/?] Domain Password_options
Erase Users:
AddUsers /e filename [/s:x] [/?] Domain Password_options
key


Filename - The comma-delimited file that AddUsers uses for data.

/s:x - Change the delimiter character used in filename to x.

e.g. /s:~ would make the delimiter “~”



Domain - Query the Primary Domain Controller (PDC) of domain.
You can also use \Servername to specify the machine where user accounts are created or read.
AddUsers will use the local computer by default (if you do not specify Domain)

/c - Create user accounts, local groups, and global groups as specified by filename.

/d{:u} - Dump user accounts, local groups, and global groups to filename.

The (:u) is an optional switch that causes current accounts to be written


to the specified file in Unicode text format. Choosing to dump current user
accounts does not save the account’s passwords or any security information
for the accounts.
Note: Password information is not saved in a user account dump and if you
use the same file to create accounts, all passwords of newly created accounts
will be empty. To back up security information for accounts, use a Tape
Backup.
/e - Erase the user accounts specified in the file name.
CAUTION: Be careful when erasing user accounts, as it is not possible to recreate

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>

A typical output from DATE /T is “Mon 11/09/2000” but this is


dependent on the country code.
The date formats for different country codes are as follows:
Country or language CountryCode Date format Time format


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.

Date Format information in the registry

The Country Code is a setting in the registry:

This can be read using REG.exe as follows


FOR /F “TOKENS=3 delims= ” %%G IN (‘REG QUERY
“HKEY_CURRENT_USER\Control Panel\International\iCountry”’) DO (SET _country=%%G)

The date separator is also a registry setting

This can be read using REG.exe as follows


FOR /F “TOKENS=3 delims= ” %%G IN (‘REG QUERY
“HKEY_CURRENT_USER\Control Panel\International\sDate”’) DO SET _date_sep=%%G

If Command Extensions are disabled DATE will not support the /T


switch

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

To delete “Hello Big World.TXT”


DEL “Hello Big World.TXT”

To delete all files that start with the letter A


DEL A*

To delete all files that end with the letter A


DEL *A.*

To delete all files with a .DOC extension


DEL *.DOC

To delete all read only files


DEL /a:R *

To delete all files including any that are read only


DEL /F *

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%

When clearing out the TEMP directory it is not generally worthwhile


removing the subfolders too - they don’t use much space and constantly
deleting and recreating them can potentially increase fragmentation within the
Master File Table.

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:

TYPE nul > C:\examples\MyFile.txt


DEL C:\examples\MyFile.txt
Undeletable Files
Files are sometimes created with the very long filenames or reserved
names: CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3,
PRN, NUL
To delete these use the syntax: DEL \.\C:\somedir\LPT1
Alternatively SUBST a drive letter to the folder containing the file.
If a file (or folder) still appears to be ‘undeletable’ this is often caused by
the indexing service.
Right click the file you need to delete, choose properties, advanced and untick
“allow indexing” you will then be able to delete the file.
To cure the problem permanently - Control Panel, Add/Remove programs,
Win Accessories, indexing service.
Delete 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.
DELTREE

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

Normally DEL will display a list of the files deleted, if Command


Extensions are disabled; it will instead display a list of any files it cannot find.
ERASE is a synonym for DEL

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.

DevCon is not redistributable. It is provided for use as a debugging and


development tool.

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

The switches above may be preset by adding them to an environment


variable called DIRCMD.
For example: SET DIRCMD=/O:N /S

Override any preset DIRCMD switches by prefixing the switch with -


For example:
DIR *.* /-S
Upper and Lower Case filenames:
Filenames longer than 8 characters - will always display the filename with
mixed case as entered.
Filenames shorter than 8 characters - may display the filename in upper or
lower case - this may vary from one client to another (registry setting)

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.

Checking filesize during a download (to monitor progress of a large


download)
TYPE file_being_downloaded >NUL
DIR file_being_downloaded

Since TYPE won’t lock the file_being_downloaded in any way, this


doesn’t pose a threat to the download itself.
On Windows Vista and later, a list of alternate data streams can be
obtained using DIR /R, On earlier operating systems, the SysInternals utility
streams can be used instead.

DIRUSE (2K Resource Kit / XP Support


Tools)
Display disk usage
Syntax
DIRUSE [options] Folders…
Options
/M Display in Mb
/K Display in Kb
/B Display in bytes (default)
/, Use thousand separator when displaying sizes.

/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

/* Report on one level of subfolders (top-level folders)



/D Display only folders that exceed specified sizes.

/S Include detail of every subfolder in the output

/O Don’t check subfolders for quota overflow.

/V Display progress report for every subfolder


/C Use Compressed size instead of apparent size.

/L Output overflows to logfile .\DIRUSE.LOG.

/A generate an alert if quota is exceeded


(requires the Alerter service)

Note: the ‘-‘ symbol can be used in place of the ‘/’ symbol.

Example

DIRUSE /M /q:1.5 /* e:\users

DISKCOMP.com
Compare the content of two floppy disks.
Syntax
DISKCOMP floppy_drive1: floppy_drive2:

Key
floppy_drive is the drive letter

The two disks must be the same type,


e.g. both 1.44 Mb or both 720 K
If you specify the same drive letter for floppy_drive1 and floppy_drive2
- you will be prompted to enter each disk.

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.

The two disks must be the same type,


e.g. both 1.44 Mb or both 720 K
If you specify the same drive letter for floppy_drive1 and floppy_drive2
- you will be prompted to enter each disk.
DISKCOMP A: A:


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

A macro to open WordPad


DOSKEY wpad=“C:\Program Files\Windows NT\Accessories\wordpad.exe”

A macro called `d’ to run dir/w


DOSKEY d=dir/w

A macro to disable the FORMAT command


DOSKEY FORMAT=;Ive disabled the Format command

More advanced macro definitions:


$T If you put more than one command in a DOSKEY macro, use $T.
to separate them. Equivalent to & in a batch file.

$1-$9 Parameters, equivalent to %1-%9 in a batch file.

$* This represents ALL the parameters $1-9

A macro to open a file with WordPad:
DOSKEY wpad=“C:\Program Files\Windows NT\Accessories\wordpad.exe” $1
Using the above macro:
>wpad MyTextfile.txt

Save and restore macro definitions

DOSKEY macros are only saved for the current session.


The command:
doskey /macros >macros.cmd
Will list all current macro definitions into macros.cmd, edit this file and place
DOSKEY at the start of each line. Then to restore all the doskey macros setup
in the current session at a later date, just run ‘ macros.cmd’.

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.

/P: Inherit permissions from parent objects (Y/N).



/R Revoke/Delete all ACEs for the users or groups.

/S Restore the default security.
Default security for each object class is defined in the Active Directory schema.

/S /T Restore the default security on the tree of objects.

Permissions
GR: Generic Read
GE: Generic Execute
GW: Generic Write
GA: Generic All

SD: Delete an object
DT: Delete an object and all of its child objects
RC: Read security information
WD: Change security information
WO: Change owner information
LC: List the child objects of the object
CC: Create a child object•
DC: Delete a child object•
WS: Write to a self object (group membership) group object + {ObjectType | Property} = “member.”
RP: Read a property•
WP: Write to a property•
CA: Control access (normally a specific extended right for control access)
If you do not specify {ObjectType | Property} this permission will apply to all
meaningful control accesses on the object.
LO: List the object access, AD DS does not enforce this permission by default.
Grant list access to a specific object when List Children (LC) is not granted to the parent.
Deny list access to a specific object when the user or group has LC permission on the parent.

ObjectType | Property
Limit the permission to the specified object type or property.
Enter the display name of the object type or the property.
Default=all object types and properties.

For example, Grant the user rights to create all types of child objects:
/G Domain\User:CC

Grant the user rights to create only child computer objects:
/G Domain\User:CC;computer

InheritedObjectType
Limit inheritance of the permission to the specified object type.
For example, Grant only User objects to inherit the permission:
/G Domain\User:CC;;user

Object Types
User,Contact,Group,Shared Folder,Printer,Computer,Domain Controllers,OU

• If you do not specify {ObjectType | Property} to define a specific child


object type, this permission applies to all types of child objects; otherwise, it
applies only to the child object type that you specify.
You can Grant, Deny or Delete ACEs for multiple users and groups with
a single parameter (/G /D /R), list the users/groups separated with spaces.
DS* commands are available on networked machines with the server
role A.D. Domain Services installed, Domain Controllers (or for XP users: XP
Professional).
Examples
Grant Generic Read (GR) and Generic Execute (GE) on computer
objects in the Laptops OU to Jdoe:

C:\> dsAcls “OU=Laptops,OU=AcmeCo,DC=example,DC=Com” /G


Domain\JDoe:GRGE;computer

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 text into a FILE

The general syntax is


Echo This is some Text > FileName.txt
or if you want to avoid extra spaces:
Echo Some more text>FileName.txt
Echo a Variable

To display a department variable:

ECHO %_department%

An alternative is to separate with : instead of a space, this has some


performance benefits.
ECHO:%_department%
If the variable does not exist - ECHO will simply return the text
“%_department%”

This can be extended to search and replace parts of a variable or display


substrings of a variable.

Echo a file

see the TYPE command for this

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)

Alternatively using Sound Recorder or Media Player:

START/min sndrec32 /play /close %windir%\media\ding.wav

START/min mplay32 /play /close %windir%\media\ding.wav

Echo a blank line

The following command in a batch file will produce an empty line

ECHO.

To ECHO text without including a CRLF see this discussion

Echo text into a stream

Streams allow one file to contain several separate forks of information (like
the macintosh resource fork)

The general syntax is


Echo Text_String > FileName:StreamName

Only the following commands support the File:Stream syntax - ECHO,


MORE, FOR

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

If SETLOCAL is used to make variables ‘local’ to one batch script, then


those variables will be invisible to all other batch scripts unless explicitly
passed using an ENDLOCAL & SET… command.
If SETLOCAL is used without a corresponding ENDLOCAL then local
environment variables will be discarded when the batch file ends. Ending the
cmd.exe session will discard all Environment Variables both local and global.

Passing variables from one routine to another


The CMD command processor always works on a line-by-line basis, so
it will convert all %variables% into their text values before executing any of
the commands.

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%

Multiple SET commands may be added to pass multiple variables, just


prefix each with an &
Be aware that any trailing spaces will be added to the variables value.
Improving readability
The ‘ENDLOCAL & SET’ technique described above can become
difficult to read if you have a lot of SET commands all on the same line. This
can be made easier to read if you first store all the Set assignments in a single
variable (_returns) as shown below (thanks to Ilya Bobyr for this technique)
Set _returns=^
Set _return1=%_item%^&^
Set _return2=%_price%^&^
Set _return3=%_discount%^&^
Set _return4=%_delivery%
Endlocal & %_returns%
In these examples we have used the variable names _return1, _return2
etc, but you can use any names for the return variables, even re-use the exact
same variable name inside and outside the ENDLOCAL command (SET
_price=%_price%)

EVENTCREATE (Windows 2003/2008)


Add a message to the Windows event log, requires administrator rights.
Syntax
EVENTCREATE [/S system [/U username [/P [password]]]] /ID eventid
[/L logname] [/SO srcname] /T type /D description

Key:
/S system The remote system to connect to.

/U [domain\]user User credentials under which to execute.

/P [password] Password for user, will prompt if omitted.

/L logname The event log to create an event in.

/T type The type of event to create: SUCCESS, ERROR, WARNING, INFORMATION.

/SO source The source to use for the event A text string that represents the application
or component that is generating the event. Default=‘eventcreate’

/ID id Event ID, a number between 1 - 1000.

/D description Description text for the new event.

/? Help

Examples:

Add an ERROR to the Application log:


C:\> EVENTCREATE /T ERROR /ID 1000 /L APPLICATION /D “My
application error mesaage”

Add a WARNING to the Application log for Application EXAMPLEApp:


C:\> EVENTCREATE /T WARNING /ID 500 /L APPLICATION /SO
EXAMPLEApp /D “Running low on diskspace”

Add an ERROR to the Application log on Server401:


C:\> EVENTCREATE /S Server401 /T ERROR /ID 250 /L APPLICATION
/D “Something bad happened”

Add an ERROR to the Application log on Server401:


C:\> EVENTCREATE /S Server401 /U billg /P password /ID 250 /T ERROR
/L APPLICATION /D “Something bad happened”

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.

To compare sets of files, use wildcards in pathname1 and pathname2


parameters.
Powershell also has an Alias FC for the Format-Custom cmdlet,
therefore to run the ‘old’ FC under powershell you need to explicitly run
C:\windows\system32\fc.exe
To identify 2 identical files use this syntax:
FC file1.txt file2.txt | FIND “FC: no dif” > nul
IF ERRORLEVEL 1 goto :s_files_are_different

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:

If names.txt contains the following:


Joe Bloggs, 123 Main St, Dunoon
Arnold Jones, 127 Scotland Street, Edinburgh

To search for “Jones” in names.txt


FIND “Jones” names.txt


–––- NAMES.TXT
Arnold Jones, 127 Scotland Street, Edinburgh

If you want to pipe a command into FIND use this syntax


TYPE names.txt | FIND “Jones”

You can also redirect like this


FIND /i “Jones” < names.txt >logfile.txt

To search a folder for files that contain a given search string:


FOR %G IN (*.txt) do (find /n /i “SearchWord” “%G”)

Searching from Windows Explorer


Because the built-in Windows XP File Search does not search all files
you may want to add a find script to the Send To folder. Alternatively Agent
Ransack or other search utilities will search all files.
Bugs/Limitations
Although FIND can be used to scan large files, it will not detect any string
that is positioned more than 1070 characters along a single line (with no
carriage return) This makes it of limited use in searching binary or XML file
types.

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

The .* expression may be useful within a larger expression, for example


f.*ing will match any string beginning with F and ending with ing.

Examples:

Search for “granny” OR “Smith” in MyFile.txt


FINDSTR “granny Smith” MyFile.txt
Search for “granny Smith” in MyFile.txt (effectively the same as the FIND
command)
FINDSTR /C:“granny Smith” MyFile.txt

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:

FINDSTR /s /i smith *.*

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:

FINDSTR /b /n /c:” *smith” MyFile.txt

Finding a string only if surrounded by the standard delimiters


Find the word “computer”, but not the words “supercomputer” or
“computerise”:

FINDSTR “\<computer\>” MyFile.txt

Find any words that begin with the letters ‘comp’, such as ‘computerise’ or
‘compete’

FINDSTR “\<comp.*” MyFile.txt


Literal search

Searching a text file that contains the following


The quick brown fox
The darkbrown fox
The really *brown* fox
FINDSTR /r .*brown MyFile.txt
or
FINDSTR .*brown MyFile.txt
Will both match the word “brown” in all 3 lines
FINDSTR /L *brown* MyFile.txt
Will only match the last string

Using a script file

Multiple search criteria can be specified with a script file /G.


Multiple files to search can be specified with a source file /F.

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:

FINDSTR /g:Crit.txt /f:Files.txt> Results.txt


Errorlevel
When an item is not found FINDSTR will return an errorlevel >0
Echo 12G6 |FindStr /R “[0-9]”
If %ERRORLEVEL% EQU 0 echo The string contains one or more numeric
characters
Echo 12G6 |FindStr /R “[^0-9]”
If %ERRORLEVEL% EQU 0 echo The string contains one or more non
numeric characters
Bugs
In early versions of FindStr /F:file a path length of more than 80 chars will be
truncated.

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=* will cause all items on each line to be processed

tokens=3* will cause the 3rd and all subsequent items on each line to be
processed

Each token specified will cause a corresponding parameter letter to be


allocated.

If the last character in the tokens= string is an asterisk, then additional


parameters are allocated for all the remaining text on the line.

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

FOR /F “tokens=1,3 delims=,” %%G IN (weather.txt) DO @echo %%G


%%H

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”

token1 , token2 , token3

%%G <ignored> %%H

January 02

February 15

March 25

%%G is declared in the FOR statement and %%H is implicitly declared


via the tokens= option. You can specify up to 26 tokens via the tokens= line,
provided this does not cause an attempt to declare a parameter higher than the
letter ‘Z’.

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.

Parse a text string:


A string of text will be treated just like a single line of input from a file, the
string must be enclosed in double quotes (or single quotes with usebackq).

Echo just the date from the following string


FOR /F “tokens=4 delims=,” %%G IN (“deposit,$4500,123.4,12-AUG-
09”) DO @echo Date paid %%G
Parse the output of a command:
FOR /F %%G IN (‘“C:\program Files\command.exe”’) DO ECHO
%%G
Parse the contents of a file:
FOR /F “tokens=1,2* delims=,” %%G IN (C:\MyDocu~1\mytex~1.txt)
DO ECHO %%G
FOR /F “usebackq tokens=1,2* delims=,” %%G IN (“C:\My
Documents\my textfile.txt”) DO ECHO %%G
Filenameset
To specify an exact set of files to be processed, such as all .MP3 files in
a folder including subfolders and sorted by date - just use the DIR /b
command to create the list of filenames ~ and use this variant of the FOR
command syntax.
Unicode
Many of the newer commands and utilities (e.g. WMIC) output text files
in unicode format, these cannot be read by the FOR command which expects
ASCII.
To convert the file format use the TYPE command.

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)

FOR /F processing of a command consists of reading the output from the


command one line at a time and then breaking the line up into individual
items of data or ‘tokens’. The DO command is then executed with the
parameter(s) set to the token(s) found.

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=* will cause all items on each line to be processed

tokens=3* will cause the 3rd and all subsequent items on each line to be
processed

Each token specified will cause a corresponding parameter letter to be


allocated.

If the last character in the tokens= string is an asterisk, then additional


parameters are allocated for all the remaining text on the line.

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

The same command with usebackq:


FOR /F “usebackq delims==” %G IN (`SET`) DO @Echo %G

To put the Windows Version into an environment variable


@echo off
::parse the VER command
FOR /F “tokens=4*” %%G IN (‘ver’) DO SET _version=%%G
:: show the result
echo %_version%

List all the text files in a folder


FOR /F “tokens=*” %%G IN (‘dir /b C:\docs\*.txt’) DO echo %%G

FOR /F “tokens=*” %%G IN (‘dir/b ^“c:\program files\*.txt^”’) DO echo %%G

In the example above the long filename has to be surrounded in “quotes”


these quotes have to be escaped using ^
The “tokens=*” has been added to match all parts of any long filenames
returned by the DIR command.

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 operation of the FOR command can be summarised as…


Take a set of data
Make a FOR Parameter %%G equal to some part of that data
Perform a command (optionally using the parameter as part of the
command).
Repeat for each item of data
If you are using the FOR command at the command line rather than in a
batch program, specify %parameter instead of %%parameter.
FOR Parameters

The first parameter has to be defined using a single character, I tend to use the
letter G.

e.g. FOR %%G IN …

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

FOR commands can be nested FOR %%G… DO (for %%U… do …)


when nesting commands choose a different letter for each part. you can then
refer to both parameters in the final DO command.

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

Create a new file of a specific size


FSUTIL file createnew filename

Eg : fsutil file createnew C:\testfile.txt 1000

Set the short NTFS filename for a file


FSUTIL file setshortname filename shortname

Eg : fsutil file setshortname C:\testfile.txt tes1.txt

Set the valid data length for a file


FSUTIL file setvaliddata filename datalength

Eg : fsutil file setvaliddata C:\testfile.txt 4096

Set the zero data for a file


FSUTIL file setzerodata offset=val length=val filename

offset : File offset, the start of the range to set to zeroes
length : Byte length of the zeroed range
Eg : fsutil file setzerodata offset=100 length=150 C:\Temp\sample.txt

List all drives (including mapped and Subst drives)


FSUTIL fsinfo drives

Query drive type for a drive


FSUTIL fsinfo drivetype volume pathname

Eg : fsutil fsinfo drivetype C:
ListLocalDrives.cmd - List all drives on the local computer

Query volume information


FSUTIL fsinfo volumeinfo volume pathname
Eg : fsutil fsinfo volumeinfo C:\

Query NTFS specific volume information


FSUTIL fsinfo ntfsinfo volume pathname

Eg : fsutil fsinfo ntfsinfo C:

Query file system statistics


FSUTIL fsinfo statistics volume pathname

Eg : fsutil fsinfo statistics C:

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

Find a file by user name (if Disk Quotas are enabled)


FSUTIL file findbysid user directory

Eg : fsutil file findbysid scottb C:\users

File system options:


FSUTIL behavior query option
FSUTIL behavior set option

Where option is one of:
allowextchar {0|1} Allow extended characters in filenames
disablelastaccess {0|1} Don’t generate last-access times
quotanotify NumSeconds Log quota violations, default=3600 seconds
mftzone {1|2|3|4} Set MFT Zone, multiple of 200MB
Bugcheckoncorrupt {0|1} Enable bugcheck #
disablecompression {0|1} Disable compression #
disableencryption {0|1} Disable encryption #
encryppagingfile {0|1}
memoryusage {1|2} Paged-pool memory cache, 1=default #
symlinkevaluation L2L:{0|1} Local to local symbolic links #
symlinkevaluation L2R:{0|1} Local to remote symbolic links #
symlinkevaluation R2R:{0|1} Remote to local symbolic links #
symlinkevaluation R2L:{0|1} Remote to remote symbolic links #
DisableDeleteNotify {0|1} Delete notifications for all volumes#
disable8dot3 [volumePath] sfnNum
sfnNum is between 0 and 3
0 = Create short file names (default).
1 = Don’t create short file names.
2 = Set 8.3 names on a per volume basis.
3 = Disable 8.3 names on all volumes except the system volume.

1 = enable option
0 = Disable option
# = Windows7/2008 option

Eg : FSUTIL behavior query disable8dot3
FSUTIL behavior set disablelastaccess 1

FSUTIL dirty query volume pathname

FSUTIL dirty set volume pathname

Marking a disk as dirty will prompt a Chkdsk at next boot
Eg : FSUTIL dirty query C:

Query a reparse point


FSUTIL reparsepoint query filename

Eg : fsutil reparsepoint query C:\Server

Delete a reparse point


FSUTIL reparsepoint delete filename

Eg : fsutil reparsepoint delete C:\Server

Edit an object identifier


FSUTIL objectid {query | set | delete | create}

Set sparse file properties


FSUTIL sparse queryflag filename
FSUTIL sparse setflag filename

FSUTIL sparse queryrange filename
FSUTIL sparse setrange filename

Eg : fsutil sparse queryflag “C:\My Test.txt”

Query the allocated ranges for a file


FSUTIL file queryallocranges offset=val length=val filename

offset : File Offset, the start of the range to query
length : Size, in bytes, of the range

Eg : fsutil file queryallocranges offset=1024 length=64 C:\Temp\sample.txt

To run FSUTIL, you must be logged on as an administrator or a member


of the Administrators group.
Sparse files provide a method of saving disk space for files that contain
meaningful data as well as large sections of data composed of zeros. If an
NTFS file is marked as sparse, then disk clusters are allocated only for the
data explicitly specified by the application.
e.g. The Indexing Service, stores it’s catalogs as sparse files.
With 8.3 filennames disabled you’ll notice a performance improvement
only with a large number of files (over 300,000) in relatively few folders
where a lot of the filenames start with similar names. Not having 8.3
filenames available will prevent the use of old applications such as Word 2.0
and Excel 4.0
If you have a lot of small files, you may need a larger Master File Table
to avoid MFT fragmentation:
FSUTIL behavior set mftzone 2 will reserve 25 % of the volume for the MFT.
1 = 12.5 %(default)
2 = 25%
3 = 37.5%
4 = 50%
This won’t affect existing disk partitions, after changing the mftzone
size, reboot the machine and create a new partition.
In Windows7 and Server 2008 the mft zone is allocated in blocks of
200MB:
1 = 200 MB (default)
2 = 400 MB
3 = 600 MB
4 = 800 MB
Increasing the MFT zone does not decrease the disk space available for
data files.
The last access time attribute of NTFS can slow performance, if you
disable it, the time set will simply be the Creation Time.
FSUTIL behavior set disablelastaccess 1

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.

Use `Binary’ for transferring executable program


files or binary data files e.g. Oracle

bye End the FTP session and exit ftp

cd Change the working directory on the remote host.

close End the FTP session and return to the cmd prompt.

debug Toggle debugging. When debug is on, FTP will display
every command.

delete remote-file
Delete file on remote host.

dir [remote-directory] [local-file]
List a remote directory’s files and subdirectories.
(or save the listing to local-file)

disconnect Disconnect from the remote host, retaining the ftp prompt.

get remote-file [local-file]
Copy a remote file to the local PC.

glob Toggle the use of wildcard characters in local pathnames.
By default, globbing is on.

hash Toggle printing a hash (#) for each 2K data block transferred.
By default, hash mark printing is off.

help [command]
Display help for ftp command.

lcd [directory]
Change the working directory on the local PC.
By default, the working directory is the directory in which ftp was started.

literal argument [ …]
Send arguments, as-is, to the remote FTP host.

ls [remote-directory] [local-file]
List a remote directory’s files and folders.
(short format)

mdelete remote-files [ …]
Delete files on remote host.

mdir remote-files [ …] local-file
Display a list of a remote directory’s files and subdirectories.
(or save the listing to local-file)
Mdir allows you to specify multiple files.

mget remote-files [ …]
Copy multiple remote files to the local PC.

mkdir directory
Create a directory on the remote host.

mls remote-files [ …] local-file
List a remote directory’s files and folders.
(short format)

mput local-files [ …]
Copy multiple local files to the remote host.

open computer [port]
Connects to the specified FTP server.

prompt Toggle prompting. Ftp prompts during multiple file transfers to
allow you to selectively retrieve or store files;
mget and mput transfer all files if prompting is turned off.
By default, prompting is on.

put local-file [remote-file]
Copy a local file to the remote host.

pwd Print Working Directory
(current directory on the remote host)

quit End the FTP session with the remote host and exit ftp.

quote argument [ …]
Send arguments, as-is, to the remote FTP host.

recv remote-file [local-file]
Copy a remote file to the local PC.

remotehelp [command]
Display help for remote commands.

rename filename newfilename
Rename remote files.

rmdir directory
Delete a remote directory.

send local-file [remote-file]
Copy a local file to the remote host.

status Display the current status of FTP connections and toggles.

trace Toggles packet tracing; trace displays the route of each packet

type [type-name]
Set or display the file transfer type:
`binary’ or `ASCII’ (the default)

If type-name is not specified, the current type is displayed.
ASCII should be used when transferring text files.

In ASCII text mode, character-set and end-of-line
characters are converted as necessary.

Use `Binary’ for transferring executable files.



user user-name [password] [account]
Specifes a user to the remote host.

verbose Toggle verbose mode. By default, verbose is on.

! command Run command on the local PC.

? [command] Display help for ftp command.

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

To run the above script:


FTP -s:GetFiles.ftp [hostname]
This will connect as the user:User_id with password:ftp_password

An FTP Script to publish files in binary mode:


::PutFiles.ftp

[User_id]
[ftp_password]

binary
mput *.html
cd images
mput *.gif

quit

To run the above script:


FTP -s:PutFiles.ftp [hostname]
This will connect as the user:User_id with password:ftp_password
Using the Windows GUI for FTP
Windows Explorer (not Internet Explorer) also has a built in FTP client.
Type in the address bar:
ftp://username@ftpserver.address.com
you will be prompted for the password.
You can also do
ftp://username:password@ftpserver.address.com
This is not recommended as anyone can read the password.
Secure FTP
Standard FTP does not encrypt passwords - they are sent across the
network in plain text. A more secure method is to use SecureFTP (SFTP) or
SecureCopy (SCP) Freeware clients are available

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”

Several FileTypes can be linked to the same executable application.

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.

Defining command line parameters

It is almost always necessary to supply command line parameters so that


when a document is opened not only is the relevant application loaded into
memory but the document itself also loaded into the application. To make this
happen the filename of the document must be passed back to the application.

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.

The FileType should always be created before making a File Association

For example:

FTYPE htmlfile=“C:\PROGRA~1\Plus!\MICROS~1\iexplore.exe” -nohome


ASSOC .html=htmlfile

FTYPE pagemill.html=C:\PROGRA~1\Adobe\PAGEMI~1.0\PageMill.exe
“%1”
ASSOC .html=pagemill.html

FTYPE rtffile=“C:\Program Files\Windows


NT\Accessories\WORDPAD.EXE” “%1”
ASSOC .rtf=rtffile

FTYPE word.rtf.8=“C:\Program Files\Microsoft Office\Office\winword.exe”


/n
ASSOC .rtf=word.rtf.8

Switching a File Association between multiple applications

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

Specify executable_path=nothing and the FTYPE command will delete the


executable_path for that FileType.
For example:
FTYPE htmlfile=

Backup your FileTypes


FTYPE >backup_types.txt
ASSOC >backup_ext.txt

Restore your FileTypes from a Backup

FOR /F “tokens=* delims=” %G IN (backup_types.txt) DO FTYPE %G


FOR /F “tokens=* delims=” %G IN (backup_ext.txt) DO ASSOC %G

This will recreate the CLASS id’s in the registry at HKey_Classes_Root.<file


extension>
If you put the commands above in a batch file change the %G to be %%G

Using File associations at the command line

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:

Start “My Document.doc”


“Monthly Report.doc”
JULY.DOC

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

group_name The global group.

domain_name A network domain.

\server A network server.

Examples:
GLOBAL “Domain Users” Scotland

Displays the members of the group “Domain Users” in the Scotland domain.

GLOBAL PrintUsers \9G_Server

Displays the members of the group PrintUsers on server 9G_Server.


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:

IF %1==12 GOTO MySubroutine


Echo the input was NOT 12
goto:eof

:MySubroutine
Echo the input was 12
goto:eof

Use a variable as a label

CHOICE /C:01 /m choose [Y]yes or [N]No


goto s_routine_%ERRORLEVEL%

:s_routine_0
Echo You typed Y for yes
goto:eof

:s_routine_1
Echo You typed N for no
goto:eof

Skip commands by using a variable as a :: comment (REM)

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=::

%_skip% COPY x:\update.dat


%_skip% echo Update applied

If Command Extensions are disabled GOTO will no longer recognise the
:EOF label

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.

/Logoff and /Boot will have no effect if there are no client-side


extensions called that require a logoff/reboot. /Force and /Wait parameters
will be ignored if /sync is specified.
GPUPDATE will apply new and changed policies, it will not remove an
existing setting where the policy is set to “not configured”
Example
C:\> GPUpdate /Force

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.

iCACLS.exe (2003 sp2, Vista)


Change file and folder permissions - display or modify Access Control
Lists (ACLs) for files and folders.
iCACLS resolves various issues that occur when using the older CACLS &
XCACLS
Syntax (files)
ICACLS FileName [/grant[:r] User:Permission[…]]
[/deny User:Permission[…]]
[/remove[:g|:d]] User[…]]
[/t] [/c] [/l] [/q]
[/setintegritylevel Level[…]]

Syntax (Store acls for all matching names into aclfile
for later use with /restore)
ICACLS name /save aclfile [/T] [/C] [/L] [/Q]

Syntax (restore folder)
ICACLS directory [/substitute SidOld SidNew […]]
/restore aclfile [/C] [/L] [/Q]

Syntax (Change Owner)
ICACLS name /setowner user [/T] [/C] [/L] [/Q]

Syntax (Find items with an ACL that mentions a specific SID)
ICACLS name /findsid Sid [/T] [/C] [/L] [/Q]

Syntax (Find files whose ACL is not in canonical form or
with a length inconsistent with the ACE count.)
ICACLS name /verify [/T] [/C] [/L] [/Q]

Syntax (Replace ACL with default inherited acls for all matching files)
ICACLS name /reset [/T] [/C] [/L] [/Q]

Key

/T Traverse all subfolders to match files/directories.

/C Continue on file errors (access denied) Error messages are still displayed.

/L Perform the operation on a symbolic link itself, not its target.

/Q Quiet - supress success messages.
/grant :r user:permission
Grant access rights, with :r, the permissions
will replace any previouly granted explicit permissions.
Otherwise the permissions are added.

/deny user:permission
Explicitly deny the specified user access rights.
This will also remove any explicit grant of the
same permissions to the same user.

/remove[:[g|d]] User
Remove all occurrences of User from the acl.

:g remove all granted rights to that User/Sid.

:d remove all denied rights to that User/Sid.



/setintegritylevel [(CI)(OI)]Level
Add an integrity ACE to all matching files.
level is one of L,M,H (Low Medium or High)


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

Unlike many other command-line tools, iCACLS correctly preserves the


canonical ordering of ACE entries:
Explicit denials
Explicit grants
Inherited denials
Inherited grants
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.

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:

(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)
When cacls is applied to the current folder only there is no inheritance
and so no output.
Bugs
You can’t break existing inheritance of permissions with icacls, for that
you need XCACLS.vbs.
In Windows Server 2003 SP2 there is a bug when attempting to use the
/setowner switch, which returns “Access denied”.
A limited release hotfix is available to resolve this issue (Q947870)
alternatively use SUBINACL
nb this bug is NOT present on Vista SP1 or Windows Server 2008.
Examples:

To backup the ACLs of every file in a directory type:


icacls * /save Myacl_backup.txt
Restore ACLS using a previously saved acl file:
icacls /restore Myacl_backup.txt
Change the Integrity Level (IL) of a file to High:

icacls MyReport.doc /setintegritylevel H

Grant the group FileAdmins Delete and Write DAC permissions to


Sales_Folder:
icacls Sales_Folder /grant FileAdmins:(D,WDAC)
Propagate a new permission to all files and subfolders, without using
inheritance:
(so if any of the subfolders contain specific permissions, those won’t be
overwritten)
icacls * /grant accountName:(NP)(RX) /T

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

IF ERRORLEVEL n statements should be read as IF Errorlevel >=


number
i.e.
IF ERRORLEVEL 0 will return TRUE when the errorlevel is 64
An alternative and often better method of checking Errorlevels is to use
the string syntax along with the %ERRORLEVEL% variable:
IF %ERRORLEVEL% GTR 0 Echo An error was found
IF %ERRORLEVEL% LSS 0 Echo An error was found

IF %ERRORLEVEL% EQU 0 Echo No error found


IF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE (Echo An error
was found)
IF %ERRORLEVEL% EQU 0 Echo No error found || Echo An error was
found
Note some errors are negative numbers.
When working with errorlevels in a batch file it’s a good idea to also use
SETLOCAL so that the %ERRORLEVEL% variable is reset each time the
batch file runs.
IF EXIST filename will return true if the file exists (this is not case
sensitive).

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

IF [%1]==[] ECHO Value Missing


or
IF [%1] EQU [] ECHO Value Missing

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 NOT DEFINED _example ECHO Value Missing

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

A workaround is to retrieve the substring and compare just those characters:


SET _prefix=%COMPUTERNAME:~0,3%
IF %_prefix%==SS6 GOTO they_matched
Pipes
When piping commands, the expression is evaluated from left to right, so
IF… | … is equivalent to (IF … ) | …
you can also use the explicit syntax IF (… | …)
ERRORLEVEL
To deliberately raise an ERRORLEVEL in a batch script use the EXIT
/B command.
It is possible (though not a good idea) to create a string variable called
%ERRORLEVEL% (user variable)
if present such a variable will prevent the real ERRORLEVEL (a system
variable) from being used by commands such as ECHO and IF.
To test for the existence of a user variable use SET errorlevel, or IF
DEFINED ERRORLEVEL
If Command Extensions are disabled IF will only support direct
comparisons: IF ==, IF EXIST, IF ERRORLEVEL
also the system variable CMDEXTVERSION will be disabled.

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

The %ERRORLEVEL% return code shows how many of the listed


workgroups the currently logged-in 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

A good way to utilise IFMEMBER is through conditional execution…

IFMEMBER Administrators || ECHO Error is 1 so [%Username%] is in


Admin_WG

IFMEMBER Administrators && ECHO Error is 0 so [%Username%] is NOT


in Admin_WG

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.

If the Adapter name contains spaces, use quotes: “Adapter Name”


wildcard characters * and ? allowed, see the examples below

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.

For Setclassid, if no ClassId is specified, then the ClassId is removed.


Examples:
> ipconfig … Show information.
> ipconfig /all … Show detailed information
> ipconfig /renew … renew all adapters
> ipconfig /renew EL* … renew any connection that has its
name starting with EL

> ipconfig /release *Con* … release all matching connections,
eg. “Local Area Connection 1” or
“Local Area Connection 2”

> ipconfig /setclassid “Local Area Connection” TEST
… set the DHCP class ID for the
named adapter to = TEST

Remove a running process from memory.


Syntax
KILL [option] process_id
KILL [option] task_name
KILL [option] window_title

Option
-f Force process kill

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.

In WindowsXP, KILL is replaced with the superior TASKKILL - Allowing


you to specify a remote computer, different user account etc - for more details
run TASKKILL /?

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

LABEL A: My work disk



LOCAL (*)
Display membership of local groups on remote servers or remote
domains.
Syntax
LOCAL group_name domain_name | \server
Key

group_name The local group.

domain_name A network domain.

server A network server.

Examples:

Local “Power Users” Scotland

Displays the members of the group ‘Power Users’ in the Scotland domain.

Local Administrators \9G_Server

Displays the members of the group Administrators on server 9G_Server.


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

Stop the counter


C:\> Logman.exe stop example-CPU
The above creates a file like C:\docs\example_09031235.blg

To convert this to text/CSV format:


C:\> relog C:\docs\example_09031235.blg -f csv -o proc_time.csv -t 2

We can now delete the counter (unless intending to reuse it again)


C:\> Logman.exe delete example-CPU
More examples:
logman start perf_log
logman update perf_log -si 10 -f csv -v mmddhhmm

logman create counter perf_log -c “\Processor(_Total)\% Processor Time”
logman create counter perf_log -c “\Processor(_Total)\% Processor Time” -max 10 -rf 01:00

logman create trace trace_log -nb 16 256 -bs 64 -o c:\logfile

logman create alert new_alert -th “\Processor(_Total)\% Processor Time>50”

logman create cfg cfg_log -reg “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\”
logman create cfg cfg_log -mgt “root\cimv2:SELECT * FROM Win32_OperatingSystem”

logman query providers
logman query providers Microsoft-Windows-Diagnostics-Networking

logman start process_trace -p Microsoft-Windows-Kernel-Process 0x10 win:Informational -ets
logman start process_trace -p Microsoft-Windows-Kernel-Process -mode newfile -max 1 -o
output%d.etl -ets

logman start usermode_trace -p “Service Control Manager Trace” -ul -ets
logman query usermode_trace -p “Service Control Manager Trace” -ul -ets
logman stop usermode_trace -p “Service Control Manager Trace” -ul -ets

logman start “NT Kernel Logger” -o log.etl -ets
logman start “NT Kernel Logger” -p “Windows Kernel Trace” (process,thread) -ets

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.

The date is stored in the US mm/dd/yy format (NT 4.0)

Sample batch file:

LOGTIME “begin import program”


import.exe
LOGTIME “end import program”

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.

MAPISEND (Back Office/Exchange


Resource kit)
Send email from the command line.
Syntax
MAPISEND -u “profile” -p password
-r recipient -s “subject” -m text message [options]

MAPISEND -u “profile” -p password
-r recipient -s “subject” -t text_file [options]

options
-i interactive login (prompts for profile and password)
-c cc: list
-f File Attachment - path and file name(s)
-v generates verbose output (an 8 line summary of the message)

“profile” is the profile name (user mailbox) of sender
“subject” is the subject line
“recipient” is one or more recipient(s)
If more than one recipient - separate with ‘;’ these must not be ambiguous in the default address
book.

Mapisend requires MAPI - i.e the MS Outlook client needs to be


installed.
Examples
mapisend -u “MS Exchange Settings” -p MyPassword -r billg@sun.com -s “Subject” -m “Test
message text”

mapisend -u “MS Exchange Settings” -p MyPassword -r billg@hp.com -s “Subject” -t
c:\MyMail.txt >> c:\mail.log

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:

no option - Scan the local computer.

/c domainname\computername - Scan the named computer.

/i xxx.xxx.xxx.xxx - Scan the specified IP address.

/r xxx.xxx.xxx.xxx - xxx.xxx.xxx.xxx - Scan the specified range of IP addresses.

/d domainname - Scan the named domain.



Items NOT to update

/n IIS - Skip IIS checks.

/n OS - Skip Windows operating system, IE, Office and Outlook checks.

/n Password - Skip password checks.

/n SQL - Skip SQL checks.

/n Updates - Skip security update checks.


The above can be combined, for example:
/n OS + IIS + Updates - skip IIS, Windows, and security update checks.

Security Update Scan Options

/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)

/s 1 - Suppress security update check note messages.

/s 2 - Suppress security update check note and warning messages.

/s 3 - Suppress warnings except for service packs.

/nosum - Security update checks will not test file checksums.



Output File Name

/o filename By default, the output filename uses the format “domain - computername
(date)”

Display the Results

/e - List the errors from the latest scan.

/l - List all the reports that are available.

/ls - List the reports from the latest scan.

/lr report name - Display an overview report.

/ld report name - Display a detailed report.

/v - Display security update reason codes.



Miscellaneous Options

/? - Usage help.

/qp - Do not display progress.

/qe - Do not display error list.

/qr - Do not display report list.

/q - Do not display progress, error list, or report list.

/f - Redirect the output to a file.

/unicode - Generate unicode output, useful for Japanese versions of Windows.

Early versions of this command were known as HFNETCHK, written by


shavlik technologies and supplied by Microsoft.

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 @

also many extended characters may not be recognised by older 16 bit


windows applications.
The maximum length of a full pathname (folders and filename) under NTFS
or FAT is 260 characters.

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

Make several folders with one command


C:\temp> MD Alpha Beta Gamma

will create

C:\temp\Alpha\
C:\temp\Beta\
C:\temp\Gamma\

Make an entire path


MD creates any intermediate directories in the path, if needed.
For example, assuming \utils does not exist then:
MD \utils\downloads\Editor

is the same as:

md \utils
cd \utils
md downloads
cd downloads
md Editor


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

MKDIR is a synonym for MD


MKLink (Vista) or LinkD (*)


Create a symbolic link to a directory or a file.
Syntax
MKLINK [[/D] | [/H] | [/J]] Link Target

LINKD Link [/D] Target

Key:

/H Create a hard link instead of a symbolic link.

/J Create a Directory Junction.

Link The new symbolic link name.

Target The path (relative or absolute) that the new link refers to.

/D MKLINK /D will create a Directory symbolic link. (default is file)
LINKD /D will delete Link, regardless of whether a link exists

To display the target name targeted by a Link run: LINKD Link.


The Target for LinkD may be a destination directory or a Windows 2000
device or any valid Windows 2000 name.
By default, only administrators can create symbolic links.
It is possible (but not advisable) to create links that point to each other in a
loop, or a link that targets itself.
Deleting a Symbolic Link does not delete the contents of the target
folder! (unlike Hard Junction links)
Symbolic links can span volumes and can use UNC paths.
Examples:
C:\>MKlink example C:\Windows\system32\notepad.exe
C:\>Dir
C:\>Del example
C:\>MKlink /D examplefolder C:\Windows
C:\>Dir
C:\>RD examplefolder

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

Show the status of a specific device:


MODE [device]

To additionally show the status of any redirected parallel printer:


MODE [device] [/STATUS]

CMD Prompt window size

Change the CMD prompt screen size/buffer


Number of cols(characters) wide and Number of lines deep

MODE CON[:] [COLS=c] [LINES=n]

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 configure a parallel printer port (PRN, LPT1, LPT2, or LPT3):


MODE LPTn[:]=COMm[:]

To setup the parameters for a serial port (* see Start, Help, Commands for
more on this).
MODE COMm [options*]

Configure a printer connected to a parallel printer port.


mode LPTn[:] [c][,[l][,r]]
mode LPTn[:] [cols=c] [lines=l]
This allows you to configure a line printer connected to a parallel printer port.

International Settings

Change the current code page:


MODE CON[:] CP SELECT=yyy

Display the current Code page:


MODE CON[:] CP [/STATUS]
Examples:
MODE CON:cols=80 lines=25

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)

/r : Remove volume mount point directories and registry settings for


volumes that are no longer in the system,this prevents them from
being automatically mounted and given their former volume mount
point(s) when added back to the system.(Server 2008)

/n : Disable automatic mounting of new basic volumes.(Server 2008)
New volumes are not mounted automatically when added to the system.

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.

To use MOVEUSER, you must be logged in with admin rights to create


and modify user accounts on both the source and target machine.
Examples
MOVEUSER fred MyDomain\newfred

Or if the account ‘fred’ is on the remote PC called ‘wks0123’


MOVEUSER fred MyDomain\newfred /c:\wks0123

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.

Windows installer versions

Windows NT can support version 1.1 or version 1.2


Windows 2K includes version 1.1
Windows XP Sp1 /Server 2003 include version 2.0
Windows XP SP2 includes version 3.0

Updates to msiexec can be downloaded from MSDN.


DO NOT use the domain controller Sysvol folder as a Windows Installer
installation point, doing so may result in the following error when you attempt
to run the Windows Installer (.msi) package:
This installation package could not be opened. Verify that the package
exists and that you can access it, or contact the application vendor to verify
that this is a valid Windows Installer package.
This is because the Sysvol folder is created with the
SHI1005_FLAGS_RESTRICT_EXCLUSIVE_OPENS attribute, which
prevents it from being exclusively locked by Windows Installer. Having
locked files on a SYSVOL would create Active Directory directory service
synchronization problems.

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\

Msinfo32 is a replacement for WINMSD


Examples:
Start System Information with all available information displayed, except
Loaded Modules:
msinfo32 /categories +all -loadedmodules
View System Information for a remote computer with a UNC name of
Server64:
msinfo32 /computer Server64
List all the available category IDs:
msinfo32 /showcategories
Display only System Summary information and create an .nfo file called
summary.nfo containing the same information:
msinfo32 /nfo summary.nfo /categories +systemsummary
Display resource conflict information and create an .nfo file called
conflicts.nfo containing the same information:
msinfo32 /nfo conflicts.nfo /categories
+componentsproblemdevices+resourcesconflicts+resourcesforcedhardware
Open System Information in History view:
msinfo32 /pch

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 /console option only works when connecting to an Windows XP


Professional or Windows Server 2003 computer.
When connected to a remote desktop, the key combination Ctrl-Alt-
END will send Ctrl-Alt-Del to the remote client.
Examples:

MSTSC /v:MyServer /f /console


MSTSC /v:127.0.0.1 /w:1024 /h:768
MSTSC /v:MyServer /w:800 /h:600
MSTSC /edit filename.rdp
On the Windows XP CD, under \SUPPORT\TOOLS you’ll find
MSRDPCLI.exe. This is the setup for use with 9.x/2000 machines.

MV.exe (*)
Move File - Copy a file to another location even if the file is in use
(Locked)
Syntax
MV /x /d source destination

Key
The first file name is the file to be copied and the second
the destination pathname.

/d : does not copy the file until reboot time
allows in-use files to be replaced

/x : Prevents the default action that will otherwise create a
folder called “deleted” containing a copy of the
original file.

Note that you must use a FULL pathname to each file.

The NT resource kit contains 2 versions of MV.EXE - a posix version and a


Windows NT version - they are not the same!

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)

Start the registry editor (regedt32.exe not regedit.exe)

Move to HKLM\SYSTEM\CurrentControlSet\Control\Session Manager

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

On the second line is the file to replaced with !\??\ in front,


e.g.
!\??\c:\winnt\system32\drivers\ntfs.sys

Click OK
So the complete Multi-String Data would appear like:

\??\d:\temp\ntfs.sys
!\??\c:\winnt\system32\drivers\ntfs.sys

Once the reboot is complete and the file replaced the


PendingFileRenameOperations value will be deleted from the registry

NET.exe
The NET Command is used to manage network resources as follows:

Manage Services
NET START, STOP, PAUSE, CONTINUE

Connect to a file/print Share (Drive Map)


NET USE
Manage file and printer shares
NET SHARE, VIEW
Manage open files and user sessions
NET FILE, SESSIONS

Manage Network Time


NET TIME
Manage Network Print jobs
NET PRINT

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

NETDOM.exe (Windows Server


2003/2008)
Domain Manager - Manage Machine Accounts and Passwords. NetDom
is available as part of the RSAT feature on a Windows 7 / 2008 R2 server (or
by default, with the AD DS or AD LDS server roles.)
Syntax
NETDOM ADD Add a workstation or server account to the domain
NETDOM COMPUTERNAME Manage computer names
NETDOM HELP
NETDOM JOIN Join a workstation or member server to the domain
NETDOM MoveNT4BDC Rename an NT4 backup domain controller
NETDOM MOVE Move a workstation or member server to a new domain
NETDOM QUERY Query the domain for information
NETDOM TRUST Manage or verify the trust relationship between domains
NETDOM REMOVE Remove a workstation or server from the domain.
NETDOM RENAMECOMPUTER Rename a computer.
NETDOM RESETPWD Reset the machine account password for a domain controller
NETDOM RESET Reset the secure connection between a workstation and a DC
NETDOM VERIFY Verify the secure connection between a workstation and a DC

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

NETSH (Network Shell)


Configure Network Interfaces, Windows Firewall, Routing & remote
access.
Syntax
NETSH [Context] [sub-Context] command

Key
The contexts and commands available vary by platform, the list below is for Windows 2008.
Use interactive mode/help (described below) to check the commands available on your machine.


= 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

In interactive mode, switch context by typing any context name:


advfirewall, bridge, firewall, http, interface, ipsec.. etc
list commands with ? exit interactive mode with Quit or Exit.
To view help for any command, type the command, followed by a space and ?
The syntax on this page is based on Windows 2008, for backwards
compatibility with XP dns is an alias for dnsserver, ip is an alias for ipv4
Examples:
Install ipmontr.dll:
C:\> netsh advfirewall net add helper ipmontr.dll

Export the fiewall policy:


C:\> netsh advfirewall export “c:\advfirewallpolicy.wfw”

Show TCP/IP settings


C:\> netsh interface ip show config
Set a static IP address (e.g. for a laptop)
C:\> Netsh interface ip set address name=“Local Area Connection”
source=static addr=192.168.0.10 mask=255.255.255.0 gateway=192.168.0.1
gwmetric=1

Set a dynamic IP address with DHCP


C:\> Netsh interface ip set address name=“Local Area Connection”
source=dhcp

Add multiple DNS servers:


C:\> Netsh interface ipv4 add dns “Local Area Connection” 10.0.0.1
C:\> Netsh interface ipv4 add dns “Local Area Connection” 10.0.0.3 index=2
index=2 adds the IP as a secondary dns server.

Set a static DNS server address:


C:\> Netsh interface ip set dns name=“Local Area Connection” source=static
addr=192.168.0.2 register=none

Set a dynamic DNS server address with DHCP:


C:\> netsh interface ip set dns name=“Local Area Connection” source=dhcp

Set a static address for the WINS server:


C:\> Netsh interface ip set wins name=“Local Area Connection”
source=static addr=192.168.100.3

To configure WINS from DHCP:


C:\> Netsh interface ip set wins name=“Local Area Connection” source=dhcp

Backup the local DHCP server configuration to a file:


C:\> netsh dump dhcp > C:\backupDHCPconfig.dat
You can use this backup file to recreate the DHCP server with Netsh .

Work against a remote machine:


C:\> netsh set machine server64

Backup the current network interface configuration to a file:


C:\> netsh dump interface > c:\backupInterfaceConfig.dat

Restore network interface configuration from a file:


C:\> netsh exec c:\backupInterfaceConfig.dat
Run Netsh from Powershell (returns a Text object you can manipulate)
PS C:\> $myFWstate=netsh firewall show state
PS C:\> $myFWstate -match “disable”
Disable Network auto-tuning (certain routers and networking devices
perform better with this off.)
PS C:\> netsh interface tcp set global autotuning=disabled
Enable Network auto-tuning (certain routers and networking devices
perform better with this on.)
PS C:\> netsh interface tcp set global autotuning=normal

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:

Mon Mar 06 14:58:48 2000 your message here


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.

NTBackup has a reputation for being clumsy and unreliable, Microsoft


Data Protection Manager is a more robust solution for Windows backup and
recovery. Third party and cross platform tools are also available: List of
backup software
NT Backup was discontinued in Windows Vista/Windows 7.

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

NTRIGHTS.exe (Resource Kit,


2000/2003)
Edit user account Privileges.
Syntax
NTRIGHTS +r Right -u UserOrGroup [-m \Computer] [-e Entry]

NTRIGHTS -r Right -u UserOrGroup [-m \Computer] [-e Entry]

Key:

+/-r Right Grant or revoke one of the rights listed below.

-u UserOrGroup Who the rights are to be granted or revoked to.

-m \Computer The computer (machine) on which to perform the operation.
The default is the local computer.

-e Entry Add a text string ‘Entry’ to the computer’s event log.

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)

System Admin Privileges:


Generate security audits SeAuditPrivilege
Manage auditing and security log SeSecurityPrivilege
Backup files and directories SeBackupPrivilege
Add workstations to the domain SeMachineAccountPrivilege
Shut down the system SeShutdownPrivilege
Force shutdown from a remote system SeRemoteShutdownPrivilege
Create a pagefile SeCreatePagefilePrivilege
Increase quotas SeIncreaseQuotaPrivilege
Restore files and directories SeRestorePrivilege
Change the system time SeSystemTimePrivilege
Manage the files on a volume SeManageVolumePrivilege (Win XP only)
Take ownership of files/objects SeTakeOwnershipPrivilege
Enable computer/user accounts
to be trusted for delegation SeEnableDelegationPrivilege
Remove computer from docking station SeUndockPrivilege

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)

To run ntrights you need to be an administrator, to change privileges


remotely (-m option) you need to have administrator rights on the machine
being changed.
To change permissions for a large number of users, add them to a domain
workgroup and grant the privileges to the group.
The group policy editor can be used to view these privileges in a GUI.

On a Windows 2008 Server (or Vista), allowing logon through Terminal


Services (SeRemoteInteractiveLogonRight) requires an extra step: Control
Panel > System > ‘Remote Settings’ > ‘Select Users’ button, and then add
users/groups.
Examples:
Allow all members of the local ‘Users’ group to logon locally
ntrights -u Users +r SeInteractiveLogonRight
Allow all members of the ‘Admin_RDP’ group to logon remotely via
RDP to “server64”, also log this security change in the event log:
ntrights -u MyDom\Admin_RDP +r SeRemoteInteractiveLogonRight -m
\server64 -e “Added RDP rights for Admin_RDP”
Allow all members of the domain group ‘Admin_General’ to shutdown
this computer.
ntrights -u MyDom\Admin_General +r SeShutdownPrivilege
Allow the domain user ‘JDoe’ to shutdown the machine ‘Server64’
ntrights -u MyDom\JDoe +r SeShutdownPrivilege -m \Server64
Specifically deny local logon rights to Henry:
ntrights -u Henry +r SeDenyInteractiveLogonRight

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.

Administrator privileges are required to run the OPENFILES command.


This can be used to detect if the current user is an Admin OPENFILES > nul
will set %ERRORLEVEL% = 1 if the user is not an administrator - see this
forum thread.
Running openfiles.exe from within powershell allows the output to be
assigned to a variable.
Examples
PS C:\> openfiles /query
PS C:\> openfiles /query /fo table /nh
PS C:\> $file_list = openfiles /query /s Server64 /fo CSV /v /nh
C:\> openfiles /query /fo list /v
C:\> openfiles /query /s Server64 /u EXAMPLEDom\FileAdmin /p
password1

PS C:\> openfiles /disconnect /id 1


PS C:\> openfiles /disconnect /a mike
C:\> openfiles /disconnect /o read/write
C:\> openfiles /disconnect /op “c:\work\finance.xls”
C:\> openfiles /disconnect /s Server64 /u EXAMPLEDom\FileAdmin /id 5
C:\> openfiles /disconnect /s Server64 /u EXAMPLEDom\FileAdmin /p
password1 /id *

PERMS.exe (Windows 2000)


Display a user’s ACL access permissions for a file. Output from PERMS
may be misleading in cases where a user has inherited permission through
membership of a workgroup.
Syntax
PERMS [account] [path] options


Key

account : username or [domain\|computer\]username

path : name of a file or folder in any legal format
including UNC names
Wildcards are permitted.

/i : interactively logged on to the computer
where the path resides.
(rather than being connected via the network)

/s : include subfolders

Access Description

R Read file/folder.

W Write file/folder.

X Execute file.

D Delete file or folder. May be inherited from the parent folder
via ‘Delete Subfolder and Files’ permission.

P Change Permission.

O Take Ownership.

A General All

- No Access

* The specified user is the owner of the file or folder.

# A group the user is a member of owns the file or folder.

? Permisssions cannot be determined.

PAUSE
Pause the execution of a batch file
Syntax
PAUSE

Displays the message “Press any key to continue …”

To suppress the message use PAUSE >nul

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.

Counter is the full name of a performance counter in the


format:”\Computer\Object(Instance)\Counter”
e.g. “\Server1\Processor(0)\% User Time”.
Examples
Display % Processor time until interrupted:
C:\> typeperf “\Processor(_Total)\% Processor Time”
Gather 600 samples of % Processor time on the local computer (this will
take 10 minutes):
C:\> typeperf “\processor(_Total)\% Processor Time” -O
C:\EXAMPLEdemo1.csv -SC 600
Gather samples of all the counters listed in counters.txt :
C:\> typeperf -cf counters.txt -si 5 -sc 50 -o C:\EXAMPLEdemo2.csv

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

Check if a host is reachable:


PING Server64 |find “TTL=” && ECHO MyHost found
Check if a host is not reachable:
PING Server64 |find “TTL=” || ECHO MyHost not found

Test which iSCSI IP on a specific NIC is functioning or if a specific teamed


NIC is operating as it should:
Ping –S (Source IP: XXX.XXX.XXX.XXX) (Destination IP:
XXX.XXX.XXX.XXX)
Ping –S 10.5.7.64 10.5.7.1

Ping a website 5 times:


PING -n 5 -w 7500 www.microsoft.com

Script to monitor your connection to a website (example.com) every 15


seconds:
@Echo off
Echo Logging ping responses, press CTRL-C to stop
:start
Ping -n 1 example.com | find “TTL=” >>c:\pingtest.txt
Echo .
Ping -n 16 127.0.0.1>nul
goto start

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

Powercfg must be run from an elevated command prompt.


The most common cause of problems with power saving/hibernation is
an incompatible device driver, diagnose this by disabling each device in turn
(with -deviceDisableWake)
When activating Power Saving across an organisation, it is important to
ensure that software updates (security patches and antivirus) are not disrupted.
WSUS can be configured to install updates when workstations are available
and Scheduled Tasks can be set to Wake the machine when needed.
Power scheme GUIDs
The use of GUIDs avoids any problems with internationalisation when
applying Power Saving to non-english versions of Windows. The three built-
in power schemes have the GUIDs listed below:
SCHEME_MAX = Power saver (Max power saving)
SCHEME_BALANCED = Balanced (Typical)
SCHEME_MIN = High performance (Min power saving)
Examples
List all Aliases:
C:\> powercfg -aliases
a1841308-3541-4fab-bc81-f71556f20b4a SCHEME_MAX
8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c SCHEME_MIN
381b4222-f694-41f0-9685-ff5bb260df2e SCHEME_BALANCED
fea3413e-7e05-4911-9a71-700331f1c294 SUB_NONE
238c9fa8-0aad-41ed-83f4-97be242c8f20 SUB_SLEEP
29f6c1db-86da-48c5-9fdb-f2b67b1f44da STANDBYIDLE
9d7815a6-7ee4-497e-8888-515a05f02364 HIBERNATEIDLE
94ac6d29-73ce-41a6-809f-6363ba21b47e HYBRIDSLEEP
d4c1d4c8-d5cc-43d3-b83e-fc51215cb04d REMOTEFILESLEEP
7516b95f-f776-4464-8c53-06167f40cc99 SUB_VIDEO
Retrieve the currently active power scheme
C:\> Powercfg -getactivescheme

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”

Set the ‘Power saver’ scheme


C:\> Powercfg -SETACTIVE SCHEME_MAX

Create a Custom Power scheme and set it as active


Set _Custom_Power=B1234567-EXAMPLE-EXAMPLE-EXAMPLE-
F00000111AAA
Powercfg -DUPLICATESCHEME SCHEME_MAX %_Custom_Power%
Powercfg -CHANGENAME %_Custom_Power% “EXAMPLE Power
Scheme “
Powercfg -SETACTIVE %_Custom_Power%
Disable the sleep button (for the users current power scheme)
For /f “tokens=2 delims=:(” %%G in (‘powercfg -getActiveScheme’) do (
Powercfg -setAcValueIndex %%G sub_buttons sButtonAction 0
Powercfg -setActive %%G
)
Disable the sleep button (for all available power schemes):
For /f “skip=2 tokens=2,4 delims=:()” %%G in (‘powercfg -list’) do (
Powercfg -setAcValueIndex %%G sub_buttons sButtonAction 0
if “%%H” == ” *” Powercfg -setActive %%G

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.

To delete a print job:

Use Control Panel, Printers (GUI) or use


NET PRINT job# /DELETE

It is possible to delete the spool .spl and .shd files from


%SystemRoot%\system32\spool\PRINTERS but this should be a last resort,
you may need to stop the spooler service first.
Status Messages
Most modern laser printers have a status display panel, the ‘Ready’
message can be changed using HP Job Language (PCL/PJL) like this:
Echo @PJL RDYMSG DISPLAY =“Ready Message” >\server\printQ
e.g.
Echo @PJL RDYMSG DISPLAY =“Ready Printer64” >\printserv1\printer64
It’s not essential to include the word “Ready” in the ready message, but
the status display has 16 characters, which is usually enough space for
“Ready” plus the printer Name/Number. e.g. “Ready Printer123”, “Ready
Prn1234567”, “Ready #123-45678” etc
Note that when a printer error or jam occurs the status message will
change, so adding a printer identifier to the status display does not replace the
need for a physical label. It can still be very useful when the physical label is
wrong or missing.
Get a list of all printer share names for a print server: net view
\printserv1
Printing requires the Spooler service to be running

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

PRNCNFG.VBS (XP and .Net)


Display, configure or rename a printer.
To display configuration information about a printer:

cscript prncnfg.vbs -g [-s RemoteComputer]
-p PrinterName
[-u UserName -w Password]

To configure a printer:

cscript prncnfg.vbs -t [-s RemoteComputer]
-p PrinterName [-r PortName] [-l Location]
[-m Comment] [-h ShareName] [-f SeparatorText]
[-y DataType] [-st StartTime] [-ut EndTime] [-o Priority]
[-i DefaultPriority] [{+ | -}shared] [{+ | -}direct]
[{+ | -}published] [{+ | -}hidden] [{+ | -}rawonly]
[{+ | -}queued] [{+ | -}keepprintedjobs]
[{+ | -}workoffline] [{+ | -}enabledevq]
[{+ | -}docompletefirst][{+ | -}enablebidi]

To change the name of a printer

cscript prncnfg.vbs -x [-s RemoteComputer]
-p PrinterName -z NewPrinterName
[-u UserName -w Password]

Parameters

-s RemoteComputer
The name of the remote computer that manages the printer.

-p PrinterName
The name of the printer.

-u UserName -w Password
An account with permission to connect WMI services to the computer
that hosts the printer. e.g. A member of the Administrators group.

-r PortName
The port to which the printer is connected.
If this is a parallel or a serial port, then use the ID of the port
(for example, LPT1 or COM1). If this is a TCP/IP port, then use the
port name that was specified when the port was added.

-l Location
The printer location, such as “Copier Room.”

-m Comment
A comment string.

-h ShareName
The share name.

-f SeparatorText
A file that contains the text that appears on the separator page.

-y DataType
Data types that the printer can accept.

-st StartTime
Specify a time of the day after which the printer is available.
If you send a document to a printer when it is unavailable, the
document is held (spooled) until the printer becomes available.
Specify time as a 24-hour clock. e.g. 2300

-ut EndTime
Specify a time of the day after which the printer is no longer available.

-o Priority
A priority that the spooler uses to route print jobs.
A print queue with a higher priority receives all its
jobs before any queue with a lower priority.

-i DefaultPriority
The default priority assigned to each print job.

{+ | -}shared
Is this printer is shared on the network.

{+ | -}direct
Is the document to be sent directly to the printer without being spooled.

{+ | -}published
Is this printer to be published in Active Directory.
If you publish a printer, other users can search for it based on its location
and capabilities, such as color printing and stapling.

{+ | -}hidden
Reserved function.

{+ | -}rawonly
Are only raw data print jobs to be spooled on this queue.

{+ | -}queued
Do not begin to print until after the last page of the document is spooled.
The printing program is unavailable until the document has finished printing.
This option ensures that the whole document is available to the printer.

{+ | -}keepprintedjobs
Retain documents after they are printed.
Allows a user to resubmit a document to the printer from the print queue.

{+ | -}workoffline
Allow sending print jobs when computer is not connected to the network.

{+ | -}enabledevq
Print jobs that do not match the printer setup (for example, PostScript files
spooled to non-PostScript printers) should be held in the queue rather than
being printed.

{+ | -}docompletefirst
Allocate jobs to a printer as soon as thay are spooled.
If this option is disabled, the spooler always sends higher priority
jobs to their respective queues first.
You should enable this option if you want to maximize printer efficiency
at the cost of job priority.

{+ | -}enablebidi
Send bi-directional status information to the spooler.

To get online help for this .VBS Script change to the directory (CD) where
it’s installed (\windows\system32) and run PRNCNFG -?

PRNMNGR (XP and above)


Display, add, remove or set default printer.
Syntax
PRNMNGR [-options] [-s server][-p printer_name][-m driver model]

[-r port][-u user_name][-w password]


Options

-l list printers

-a add local printer
-ac add printer connection

-g get the default printer
-t set the default printer
-d delete printer
-x delete all printers

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

PROMPT is implemented as a hidden* environment variable called


PROMPT: ECHO %prompt%
Knowing this you can force an over-ride of the CMD prompt for all sessions
by setting a permanent environment variable with the appropriate prompt text.
e.g.

SETX PROMPT $M$_$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 (part of PsTools – Please note you


have to download PsExec from Microsoft
site)
Execute a command-line process on a remote machine.
Syntax
psexec \computer[,computer[,..] [options] command [arguments]

psexec @run_file [options] command [arguments]

Options:

computer The computer on which psexec will run command. Default = local system
To run against all computers in the current domain enter “\*”

@run_file Run command on every computer listed in the text file specified.

command Name of the program to execute

arguments Arguments to pass (file paths must be absolute paths on the target system)

-a n,n,… Set processor affinity to n. Processors are numbered as 1,2,3,4 etc
so to run the application on CPU 2 and CPU 4, enter: “-a 2,4”

-c Copy the program (command)to the remote system for execution.
-c -f Copy even if the file already exists on the remote system.
-c -v Copy only if the file is a higher version or is newer than the remote copy.

If you omit the -c option then the application must be in the system path on the remote system.

-d Don’t wait for the application to terminate.
Only use for non-interactive applications.

-e Load the user account’s profile, don’t use with the system account (-s)

-i Interactive - Run the program so that it interacts with the desktop on the remote system.

-l Limited - Run process as limited user. Only allow privs assigned to the Users group.

-n s Specify a timeout s seconds for connecting to the remote computer.

-p psswd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.

-s Run remote process in the System account.

-u user Specify a user name for login to remote computer(optional).

-w directory Set the working directory of the process (relative to the remote computer).

-x Display the UI on the Winlogon desktop (local system only).

-low, -belownormal, -abovenormal, -high or -realtime
These options will run the process at a different priority.

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:

Launch an interactive command prompt on \workstation64, the CMD prompt


window will appear locally:
psexec \workstation64 cmd
Execute IpConfig on the remote system, and display the output locally:
psexec \workstation64 ipconfig /all
Copy the program test.exe to the remote system and execute it
interactively:
psexec \workstation64 -c test.exe
Execute a program that is already installed on the remote system:
psexec \workstation64 “c:\Program Files\test.exe”
Run Internet Explorer on the local machine but with limited-user
privileges:
psexec -l -d “c:\program files\internet explorer\iexplore.exe”

PsFile (part of PsTools – also must be


acquired from Microsoft site)
Show files opened remotely, or close an open file (kill file locks)
Syntax
psfile [\Computer [-u User [-p Passwd]]] [[Id | path] [-c]]

Options:

computer The remote computer on which to list files. Default = local system


-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.

-u user Specify a username for login to remote computer(optional).

Id Identifier (as assigned by PsFile) of the file for which to display info or to close.

Path Full or partial path of files to match for information display or close.

-c Close the files identifed by ID or path.

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.

Pathping is invaluable for determining which routers or subnets may be


having network problems - it displays the degree of packet loss at any given
router or link.
Pathping sends multiple Echo Request messages to each router between
a source and destination over a period of time and computes aggregate results
based on the packets returned from each router.
Pathping performs the equivalent of the tracert command by identifying
which routers are on the path.
To avoid network congestion and to minimize the effect of burst losses,
pings should be sent at a sufficiently slow pace (not too frequently.)
When -p is specified, pings are sent individually to each intermediate
hop. When -w is specified, multiple pings can be sent in parallel. It’s therefore
possible to choose a Timeout parameter that is less than the wait Period *
Number of hops.
Firewalls
Like tracert PathPing uses Internet Control Message Protocol (ICMP) over
TCP/IP. Many firewalls will block ICMP traffic by default. If an attacker is
able to forge ICMP redirect packets, he or she can alter the routing tables on
the host and possibly subvert the security of the host by causing traffic to flow
via a path you didn’t intend.

RASDIAL (Dial Up Networking)


Manage RAS/DUN connections.
Dial a RAS connection:
RASDIAL entryname [/PHONEBOOK:PhonebookFile]
[/PHONE:PhoneNumber] [username [password|*]]
[/CALLBACK:CallBackNumber]
[/DOMAIN:domain][/PREFIXSUFFIX]

Hang up a RAS connection:
RASDIAL [entryname] /DISCONNECT

Display RAS Status:
RASDIAL

To use this command requires that Dial Up Networking Service be


installed (via Control Panel - Networking)

The default location for PhoneBook entries is \%SystemRoot%\system32\ras\



RASPHONE (Dial Up Networking)


Manage Remote Access Service (RAS) connections.
This is a part of the Dial-Up Networking service, typically used to connect a
PC to an Internet Service Provider.
Dial a RAS connection:
RASPHONE [-v] -f PhoneBook_file -d “PhoneBook_entry”

Hang up a RAS connection:
RASPHONE [-v] -f PhoneBook_file -h “PhoneBook_entry”

Display RAS Status dialogue box
RASPHONE -S

Other RAS options:
RASPHONE [-v] -f PhoneBook_file options “PhoneBook_entry”

OPTIONS
-a : Add new PhoneBook entry
-e : Edit an existing PhoneBook entry
-c : Clone an existing PhoneBook entry
-r : Delete/remove an existing PhoneBook entry
-v : Disable - ‘grey out’ the option to rename the PhoneBook_entry

To use this command requires that Dial Up Networking Service be


installed (via Control Panel - Networking)
The default location for PhoneBook entries is %SystemRoot%\System32\ras\

RECOVER
Recover a damaged file from a defective disk.
Syntax
RECOVER [drive:][path]filename

Recover is designed to help in the case of hardware failure. When a drive


fails the failure is not always total, in other words you may be able to read
some of the files but not others, and some files will be only partly readable.

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.

Recover does not allow you to undelete a file.


Recover the files one at a time.

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.

Only HKLM and HKU are available on remote machines.



FileName : The filename to save or restore a registry hive.

KeyName : A key name to load a hive file into. (Creating a new key)

/S : Query all subkeys and values.

/S Separator : Character to use as the separator in REG_MULTI_SZ values
the default is “\0”

/t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ

Output : /od (only differences) /os (only matches) /oa (all) /on (no output)

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

How to add keys and values from the registry:

Create a text file like this:


Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SomeKey]
“SomeStringValue”=“Hello”

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

Compare the Registry of two machines


Windiff is your friend, this simple GUI utility from the resource kit will
list all the differences.

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):

REGSVR32 “C:\Program Files\Common Files\Microsoft


Shared\DAO\DAO360.DLL”

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

Some general rules are:


Semicolon character is an end-of-line comment character, provided it is the
first non-blank character on a line

Backslash character is a line continuation character. All characters from the


backslash up to but not including the first non-blank character of the next line
are ignored. If there is more than one space before the line continuation
character, it is replaced by a single space.

Indentation is used to indicate the tree structure of registry keys The


REGDMP program uses indentation in multiples of 4. You may use hard tab
characters for indentation, but embedded hard tab characters are converted to
a single space regardless of their position

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.

Key names can be followed by an Access Control List (ACL) which is a


series of decimal numbers, separated by spaces, bracketed by a square
brackets (e.g. [8 4 17]). The valid numbers and their meanings are:
1 - Administrators Full Access
2 - Administrators Read Access
3 - Administrators Read and Write Access
4 - Administrators Read, Write and Delete Access
5 - Creator Full Access
6 - Creator Read and Write Access
7 - World Full Access
8 - World Read Access
9 - World Read and Write Access
10 - World Read, Write and Delete Access
11 - Power Users Full Access
12 - Power Users Read and Write Access
13 - Power Users Read, Write and Delete Access
14 - System Operators Full Access
15 - System Operators Read and Write Access
16 - System Operators Read, Write and Delete Access
17 - System Full Access
18 - System Read and Write Access
19 - System Read Access
20 - Administrators Read, Write and Execute Access
21 - Interactive User Full Access
22 - Interactive User Read and Write Access
23 - Interactive User Read, Write and Delete Access

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_SZ and REG_EXPAND_SZ, if you want leading or trailing


spaces in the value text, surround the text with quotes. The value text
can contain any number of imbedded quotes, and REGINI will ignore them,
as it only looks at the first and last character for quote characters.

For REG_MULTI_SZ, each component string is surrounded by quotes. If you


want an imbedded quote character, then double quote it, as in string2 above.

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.

Whenever specifying a registry path, either on the command line or in an


input file, the following prefix strings can be used:
HKEY_LOCAL_MACHINE
HKEY_USERS
HKEY_CURRENT_USER
USER:


Each of these strings can stand alone as the key name or be followed
a backslash and a subkey path.

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

RENAME is a synonym for REN

You cannot specify a different drive or path for `new_filename` - use the
MOVE command instead.

Both the source and/or destination may include wildcards.


Examples
Rename Monday.txt as Tuesday.txt
C:\> REN Monday.txt Tuesday.txt
Rename all text files in the current folder to have the extension .BAK
C:\> REN *.txt *.BAK

Rename Monday.txt as Monday.BAK


C:\> REN Monday.txt *.BAK

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.

RD c:\docs\Jan c:\docs\Feb “c:\My Documents\Mar”

RMDIR is a synonym for RD



ROBOCOPY.exe (XP Resource


Kit/Standard Windows 7 command)
Robust File and Folder Copy.
By default Robocopy will only copy a file if the source and destination have
different time stamps or different file sizes.
Syntax
ROBOCOPY Source_folder Destination_folder [files_to_copy] [options]

Key
file(s)_to_copy : A list of files or a wildcard.
(defaults to copying *.*)

Source options
/S : Copy Subfolders.
/E : Copy Subfolders, including Empty Subfolders.
/COPY:copyflag[s] : What to COPY (default is /COPY:DAT)
(copyflags : D=Data, A=Attributes, T=Timestamps
S=Security=NTFS ACLs, O=Owner info, U=aUditing info).
/SEC : Copy files with SECurity (equivalent to /COPY:DATS).
/DCOPY:T : Copy Directory Timestamps. ##
/COPYALL : Copy ALL file info (equivalent to /COPY:DATSOU).
/NOCOPY : Copy NO file info (useful with /PURGE).

/A : Copy only files with the Archive attribute set.
/M : like /A, but remove Archive attribute from source files.
/LEV:n : Only copy the top n LEVels of the source tree.

/MAXAGE:n : MAXimum file AGE - exclude files older than n days/date.
/MINAGE:n : MINimum file AGE - exclude files newer than n days/date.
(If n < 1900 then n = no of days, else n = YYYYMMDD date).

/FFT : Assume FAT File Times (2-second date/time granularity).
/256 : Turn off very long path (> 256 characters) support.

Copy options
/L : List only - don’t copy, timestamp or delete any files.
/MOV : MOVe files (delete from source after copying).
/MOVE : Move files and dirs (delete from source after copying).

/Z : Copy files in restartable mode (survive network glitch).
/B : Copy files in Backup mode.
/ZB : Use restartable mode; if access denied use Backup mode.
/IPG:n : Inter-Packet Gap (ms), to free bandwidth on slow lines.

/R:n : Number of Retries on failed copies - default is 1 million.
/W:n : Wait time between retries - default is 30 seconds.
/REG : Save /R:n and /W:n in the Registry as default settings.
/TBD : Wait for sharenames To Be Defined (retry error 67).

Destination options

/A+:[RASHCNET] : Set file Attribute(s) on destination files + add.
/A-:[RASHCNET] : UnSet file Attribute(s) on destination files - remove.
/FAT : Create destination files using 8.3 FAT file names only.

/CREATE : CREATE directory tree structure + zero-length files only.
/DST : Compensate for one-hour DST time differences ##
/PURGE : Delete dest files/folders that no longer exist in source.
/MIR : MIRror a directory tree - equivalent to /PURGE plus all subfolders (/E)

Logging options
/L : List only - don’t copy, timestamp or delete any files.
/NP : No Progress - don’t display % copied.
/LOG:file : Output status to LOG file (overwrite existing log).
/UNILOG:file : Output status to Unicode Log file (overwrite) ##
/LOG+:file : Output status to LOG file (append to existing log).
/UNILOG+:file : Output status to Unicode Log file (append) ##
/TS : Include Source file Time Stamps in the output.
/FP : Include Full Pathname of files in the output.
/NS : No Size - don’t log file sizes.
/NC : No Class - don’t log file classes.
/NFL : No File List - don’t log file names.
/NDL : No Directory List - don’t log directory names.
/TEE : Output to console window, as well as the log file.
/NJH : No Job Header.
/NJS : No Job Summary.

Repeated Copy Options
/MON:n : MONitor source; run again when more than n changes seen.
/MOT:m : MOnitor source; run again in m minutes Time, if changed.

/RH:hhmm-hhmm : Run Hours - times when new copies may be started.
/PF : Check run hours on a Per File (not per pass) basis.

Job Options
/JOB:jobname : Take parameters from the named JOB file.
/SAVE:jobname : SAVE parameters to the named job file
/QUIT : QUIT after processing command line (to view parameters).
/NOSD : NO Source Directory is specified.
/NODD : NO Destination Directory is specified.
/IF : Include the following Files.

Advanced options you’ll probably never use
/EFSRAW : Copy any encrypted files using EFS RAW mode. ##
/MT[:n] : Multithreaded copying, n = no. of threads to use (1-128) ###
default = 8 threads, not compatible with /IPG and /EFSRAW
The use of /LOG is recommended for better performance.


/SECFIX : FIX file SECurity on all files, even skipped files.
/TIMFIX : FIX file TIMes on all files, even skipped files.

/XO : eXclude Older - if destination file exists and is the same date
or newer than the source - don’t bother to overwrite it.
/XC | /XN : eXclude Changed | Newer files
/XL : eXclude “Lonely” files and dirs (present in source but not destination)
This will prevent any new files being added to the destination.
/XX : eXclude “eXtra” files and dirs (present in destination but not source)
This will prevent any deletions from the destination. (this is the default)

/XF file [file]… : eXclude Files matching given names/paths/wildcards.
/XD dirs [dirs]… : eXclude Directories matching given names/paths.
XF and XD can be used in combination e.g.
ROBOCOPY c:\source d:\dest /XF *.doc *.xls /XD c:\unwanted /S

/IA:[RASHCNETO] : Include files with any of the given Attributes
/XA:[RASHCNETO] : eXclude files with any of the given Attributes
/IS : Include Same, overwrite files even if they are already the same.
/IT : Include Tweaked files.
/XJ : eXclude Junction points. (normally included by default).

/MAX:n : MAXimum file size - exclude files bigger than n bytes.
/MIN:n : MINimum file size - exclude files smaller than n bytes.
/MAXLAD:n : MAXimum Last Access Date - exclude files unused since n.
/MINLAD:n : MINimum Last Access Date - exclude files used since n.
(If n < 1900 then n = n days, else n = YYYYMMDD date).

/BYTES : Print sizes as bytes.

/X : Report all eXtra files, not just those selected & copied.
/V : Produce Verbose output log, showing skipped files.
/ETA : Show Estimated Time of Arrival of copied files.
## = 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

If either the source or desination are a “quoted long foldername” do not


include a trailing backslash as this will be treated as an escape character, i.e.
“C:\some path\” will fail but “C:\some path\” or “C:\some path.” or “C:\some
path” will work.
Robocopy will fail to copy files that are ‘locked’ by other users or
applications, limiting the number of retries with /R:0 will speed up large jobs.
By copying only the files that have changed, robocopy can be used to
backup very large volumes.
To limit the network bandwidth used by robocopy, specify the Inter-Packet
Gap parameter /IPG:n
This will send packets of 64 KB each followed by a delay of n Milliseconds.
ROBOCOPY will accept UNC pathnames including UNC pathnames
over 256 characters long.
/REG Writes to the registry at
HKCU\Software\Microsoft\ResKit\Robocopy
/B (backup mode) will allow Robocopy to override file and folder
permission settings (ACLs).
/XX If used in conjunction with /Purge or /Mir, this switch will take
precedence and prevent any files being deleted from the destination.
All versions of Robocopy will copy security information (ACLs) for
directories, version XP010 will not copy file security changes unless the file
itself has also changed, this greatly improves performance.
To run ROBOCOPY under a non-administrator account will require
backup files privilege, to copy security information auditing privilege is also
required, plus of course you need at least read access to the files and folders.
Robocopy is a standard command in Windows 7 and above. The
Windows Server 2003 Resource Kit Tools include Robocopy XP010, which
can be run on NT 4/ Windows 2000. Robocopy does not run on Windows 95,
or NT 3.5. (RoboCopy is a Unicode application).
Robocopy ‘Jobs’ and the ‘MOnitor source’ option provide an alternative
to setting up a Scheduled Task to run a batchfile with a RoboCopy command.
Examples:
Copy files from one server to another (auto skip files already in the
destination)
ROBOCOPY \Server1\reports \Server2\backup *.doc /S

List files over 32 MBytes in size:


ROBOCOPY C:\work /MAX:33554432 /L

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

SET _options=/R:0 /W:0 /LOG:MyLogfile.txt /NFL /NDL


:: /R:n :: number of Retries
:: /W:n :: Wait time between retries
:: /LOG :: Output log file
:: /NFL :: No file logging
:: /NDL :: No dir logging

ROBOCOPY %_source% %_dest% %_what% %_options%


Run two robocopy jobs at the same time with START /Min
Start /Min “Job one” Robocopy \FileServA\C$\Database1 \FileServeBackupA\c$\Backups
Start /Min “Job two” Robocopy \FileServB\C$\Database2 \FileServeBackupB\c$\Backups

Bugs
Version XP026 returns a success errorlevel even when it fails.

ROBOCOPY.exe (XP Resource


Kit/Standard Windows 7 command)
Robust File and Folder Copy.
By default Robocopy will only copy a file if the source and destination have
different time stamps or different file sizes.
Syntax
ROBOCOPY Source_folder Destination_folder [files_to_copy] [options]

Key
file(s)_to_copy : A list of files or a wildcard.
(defaults to copying *.*)

Source options
/S : Copy Subfolders.
/E : Copy Subfolders, including Empty Subfolders.
/COPY:copyflag[s] : What to COPY (default is /COPY:DAT)
(copyflags : D=Data, A=Attributes, T=Timestamps
S=Security=NTFS ACLs, O=Owner info, U=aUditing info).
/SEC : Copy files with SECurity (equivalent to /COPY:DATS).
/DCOPY:T : Copy Directory Timestamps. ##
/COPYALL : Copy ALL file info (equivalent to /COPY:DATSOU).
/NOCOPY : Copy NO file info (useful with /PURGE).

/A : Copy only files with the Archive attribute set.
/M : like /A, but remove Archive attribute from source files.
/LEV:n : Only copy the top n LEVels of the source tree.

/MAXAGE:n : MAXimum file AGE - exclude files older than n days/date.
/MINAGE:n : MINimum file AGE - exclude files newer than n days/date.
(If n < 1900 then n = no of days, else n = YYYYMMDD date).

/FFT : Assume FAT File Times (2-second date/time granularity).
/256 : Turn off very long path (> 256 characters) support.

Copy options
/L : List only - don’t copy, timestamp or delete any files.
/MOV : MOVe files (delete from source after copying).
/MOVE : Move files and dirs (delete from source after copying).

/Z : Copy files in restartable mode (survive network glitch).
/B : Copy files in Backup mode.
/ZB : Use restartable mode; if access denied use Backup mode.
/IPG:n : Inter-Packet Gap (ms), to free bandwidth on slow lines.

/R:n : Number of Retries on failed copies - default is 1 million.
/W:n : Wait time between retries - default is 30 seconds.
/REG : Save /R:n and /W:n in the Registry as default settings.
/TBD : Wait for sharenames To Be Defined (retry error 67).

Destination options

/A+:[RASHCNET] : Set file Attribute(s) on destination files + add.
/A-:[RASHCNET] : UnSet file Attribute(s) on destination files - remove.
/FAT : Create destination files using 8.3 FAT file names only.

/CREATE : CREATE directory tree structure + zero-length files only.
/DST : Compensate for one-hour DST time differences ##
/PURGE : Delete dest files/folders that no longer exist in source.
/MIR : MIRror a directory tree - equivalent to /PURGE plus all subfolders (/E)

Logging options
/L : List only - don’t copy, timestamp or delete any files.
/NP : No Progress - don’t display % copied.
/LOG:file : Output status to LOG file (overwrite existing log).
/UNILOG:file : Output status to Unicode Log file (overwrite) ##
/LOG+:file : Output status to LOG file (append to existing log).
/UNILOG+:file : Output status to Unicode Log file (append) ##
/TS : Include Source file Time Stamps in the output.
/FP : Include Full Pathname of files in the output.
/NS : No Size - don’t log file sizes.
/NC : No Class - don’t log file classes.
/NFL : No File List - don’t log file names.
/NDL : No Directory List - don’t log directory names.
/TEE : Output to console window, as well as the log file.
/NJH : No Job Header.
/NJS : No Job Summary.

Repeated Copy Options
/MON:n : MONitor source; run again when more than n changes seen.
/MOT:m : MOnitor source; run again in m minutes Time, if changed.

/RH:hhmm-hhmm : Run Hours - times when new copies may be started.
/PF : Check run hours on a Per File (not per pass) basis.

Job Options
/JOB:jobname : Take parameters from the named JOB file.
/SAVE:jobname : SAVE parameters to the named job file
/QUIT : QUIT after processing command line (to view parameters).
/NOSD : NO Source Directory is specified.
/NODD : NO Destination Directory is specified.
/IF : Include the following Files.

Advanced options you’ll probably never use
/EFSRAW : Copy any encrypted files using EFS RAW mode. ##
/MT[:n] : Multithreaded copying, n = no. of threads to use (1-128) ###
default = 8 threads, not compatible with /IPG and /EFSRAW
The use of /LOG is recommended for better performance.


/SECFIX : FIX file SECurity on all files, even skipped files.
/TIMFIX : FIX file TIMes on all files, even skipped files.

/XO : eXclude Older - if destination file exists and is the same date
or newer than the source - don’t bother to overwrite it.
/XC | /XN : eXclude Changed | Newer files
/XL : eXclude “Lonely” files and dirs (present in source but not destination)
This will prevent any new files being added to the destination.
/XX : eXclude “eXtra” files and dirs (present in destination but not source)
This will prevent any deletions from the destination. (this is the default)

/XF file [file]… : eXclude Files matching given names/paths/wildcards.
/XD dirs [dirs]… : eXclude Directories matching given names/paths.
XF and XD can be used in combination e.g.
ROBOCOPY c:\source d:\dest /XF *.doc *.xls /XD c:\unwanted /S

/IA:[RASHCNETO] : Include files with any of the given Attributes
/XA:[RASHCNETO] : eXclude files with any of the given Attributes
/IS : Include Same, overwrite files even if they are already the same.
/IT : Include Tweaked files.
/XJ : eXclude Junction points. (normally included by default).

/MAX:n : MAXimum file size - exclude files bigger than n bytes.
/MIN:n : MINimum file size - exclude files smaller than n bytes.
/MAXLAD:n : MAXimum Last Access Date - exclude files unused since n.
/MINLAD:n : MINimum Last Access Date - exclude files used since n.
(If n < 1900 then n = n days, else n = YYYYMMDD date).

/BYTES : Print sizes as bytes.

/X : Report all eXtra files, not just those selected & copied.
/V : Produce Verbose output log, showing skipped files.
/ETA : Show Estimated Time of Arrival of copied files.

## = 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

If either the source or desination are a “quoted long foldername” do not


include a trailing backslash as this will be treated as an escape character, i.e.
“C:\some path\” will fail but “C:\some path\” or “C:\some path.” or “C:\some
path” will work.
Robocopy will fail to copy files that are ‘locked’ by other users or
applications, limiting the number of retries with /R:0 will speed up large jobs.
By copying only the files that have changed, robocopy can be used to
backup very large volumes.
To limit the network bandwidth used by robocopy, specify the Inter-Packet
Gap parameter /IPG:n
This will send packets of 64 KB each followed by a delay of n Milliseconds.
ROBOCOPY will accept UNC pathnames including UNC pathnames
over 256 characters long.
/REG Writes to the registry at
HKCU\Software\Microsoft\ResKit\Robocopy
/B (backup mode) will allow Robocopy to override file and folder
permission settings (ACLs).
/XX If used in conjunction with /Purge or /Mir, this switch will take
precedence and prevent any files being deleted from the destination.
All versions of Robocopy will copy security information (ACLs) for
directories, version XP010 will not copy file security changes unless the file
itself has also changed, this greatly improves performance.
To run ROBOCOPY under a non-administrator account will require
backup files privilege, to copy security information auditing privilege is also
required, plus of course you need at least read access to the files and folders.
Robocopy is a standard command in Windows 7 and above. The
Windows Server 2003 Resource Kit Tools include Robocopy XP010, which
can be run on NT 4/ Windows 2000. Robocopy does not run on Windows 95,
or NT 3.5. (RoboCopy is a Unicode application).
Robocopy ‘Jobs’ and the ‘MOnitor source’ option provide an alternative
to setting up a Scheduled Task to run a batchfile with a RoboCopy command.
Examples:
Copy files from one server to another (auto skip files already in the
destination)
ROBOCOPY \Server1\reports \Server2\backup *.doc /S

List files over 32 MBytes in size:


ROBOCOPY C:\work /MAX:33554432 /L

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

SET _options=/R:0 /W:0 /LOG:MyLogfile.txt /NFL /NDL


:: /R:n :: number of Retries
:: /W:n :: Wait time between retries
:: /LOG :: Output log file
:: /NFL :: No file logging
:: /NDL :: No dir logging

ROBOCOPY %_source% %_dest% %_what% %_options%


Run two robocopy jobs at the same time with START /Min
Start /Min “Job one” Robocopy \FileServA\C$\Database1 \FileServeBackupA\c$\Backups
Start /Min “Job two” Robocopy \FileServB\C$\Database2 \FileServeBackupB\c$\Backups

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.

If the command is PRINT or DELETE. Destination or gateway can be a


wildcard (‘*’), or the gateway argument may be omitted.

An IP address mask of 0.0.0.0 means everything. (rather like the *.*


wildcard). In other words it says: When matching this pattern, don’t worry
about matching any of the bits - everything matches.

If Destination_Host contains a * or ?, it is treated as a shell pattern, and only


matching destination routes are printed. The ‘*’ matches any string, and ‘?’
matches any one char.
Examples:
157.*.1
157.*
127.*
*224*

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

Enter the password when prompted.


When you start a program with RunAs /netonly, the program will
execute on your local computer as the user you are currently logged on as, but
any connections to other computers on the network will be made using the
user account specified.
Without /netonly everything will run under the user account specified.
RunAs from Windows Explorer
Select an executable file, Shift-Right-click and select Run As..
This option can be hidden by setting
HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
HideRunAsVerb=1
ErrorLevel
The error level (%ERRORLEVEL%) returned by RunAs in Windows XP and
above: success=0, failure=1
Examples
Run mycommand.exe as the user Jdoe on domain EXAMPLEdom
Runas /user:EXAMPLEDom\jDoe “mycommand.exe”

Run CMD.exe as the Administrator on the local machine:


Runas /profile /user:DELLPC218\administrator CMD

Run Notepad.exe as the Domain Administrator on domain


EXAMPLEdom
Runas /profile /env /user:EXAMPLEDom\administrator NOTEPAD

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

To retrieve specific information from SC’s output, pipe into FIND or


FindStr
e.g.
C:\> SC query messenger | FIND “STATE” | FIND “STOPPED”

C:\> SC query messenger | FIND “STATE” | FIND “RUNNING”

The statements above will return an %ERRORLEVEL% = 1 if the text is


not found
IF errorlevel 1 GOTO :my_subroutine

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

The service control manager will normally wait up to 30 seconds to


allow a service to start - you can modify this time (30,000 milliseconds) in the
registry
HKLM\SYSTEM\CurrentControlSet\Control
ServicesPipeTimeout (REG_DWORD)
Some options only take effect at the point when the service is started e.g.
the SC config command allows the executable of a service to be changed.
When the service next starts up it will run the new executable. Config
changes requires the current user to have “permission to configure the
service”.
Examples:
SC GetKeyName “task scheduler”
SC GetDisplayName schedule
SC start schedule
SC QUERY schedule
SC QUERY type= driver
SC QUERY state= all |findstr “DISPLAY_NAME STATE” >svc_installed.txt
SC \myServer CONFIG myService obj= LocalSystem password= mypassword
SC CONFIG MyService binPath=c:\myprogram.exe obj=”.\LocalSystem” password=””

Watch out for extra spaces:


SC QUERY state= all Works
SC QUERY sTate =all Fails!

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)

To prompt for the password, specify /RP * or /RP none


The User Account under which the Schedule service runs may require
specific file access permissions, user permissions and drive mappings.
If the /RU username and /RP Password parameters match the currently logged-in user, the task
will run interactively (visible in the foreground).

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

Now delete the task:


SCHTASKS /Delete /TN “MyDailyBackup” /f

Create a daily task to run a script at 5 pm:


SCHTASKS /create /tn “My Script” /tr “\”c:\my folder\script.cmd\” arguments” /sc daily /sd
12/29/2008 /st 17:00

Task Scheduler options are stored in the registry


HKLM\SOFTWARE\Microsoft\SchedulingAgent\

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

Display variables that begin with ‘P’: SET p


Display variables that begin with an underscore SET _
Examples

Storing a text string:

C:\> SET _dept=Sales and Marketing


C:\> set _
_dept=Sales and Marketing
One variable can be based on another, but this is not dynamic
E.g.
C:\> set xx=fish
C:\> set msg=%xx% chips
C:\> set msg
msg=fish chips
C:\> set xx=sausage
C:\> set msg
msg=fish chips
C:\> set msg=%xx% chips
C:\> set msg
msg=sausage chips
Avoid starting variable names with a number, this will avoid the variable
being mis-interpreted as a parameter
%123_myvar% < > %1 23_myvar

To display undocumented system variables:


SET “

Prompt for user input


@echo off

Set /P _dept=Please enter Department:

If “%_dept%”==”” goto :sub_error

If /i “%_dept%”==“finance” goto sub_finance

If /i “%_dept%”==“hr” goto sub_hr
goto:eof

:sub_finance
echo You chose the finance dept
goto:eof

:sub_hr
echo You chose the hr dept

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%)

Deleting an environment variable

Type SET with just the variable name and an equals sign:

SET _department=

Better still, to be sure there is no trailing space after the = use:


(SET _department=)
or
SET “_department=”

Variable names can include Spaces

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

(SET _department=Some Text)


Alternatively you can do
SET “_department=Some Text”

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)

The expression to be evaluated can include the following operators:


Multiply *
Divide /
Add +
Subtract -
Modulus %
AND &
OR |
XOR ^
LSH <<
RSH >>
Multiply Variable *=
Divide Variable /=
Add Variable +=
Subtract Variable -=
AND Variable &=
OR Variable |=
XOR Variable ^=
LSH Variable <<=
RSH Variable >>=

SET /a calculations
Enclose any logical expressions in “quotes”
Several calculations can be put on one line if separated with commas.

Warning: any SET /A calculation that returns a fractional result will be


rounded down to the nearest whole integer.
Examples:
SET /A _result=2+4
(=6)

SET /A _result=5
(=5)
SET /A _result+=5
(=10)

SET /A _result=“2<<3”
(=16) { 2 Lsh 3 = binary 10 Lsh 3 = binary 10000 = decimal 16 }

SET /A _result=“5%%2”
(=1) { 5/2 = 2 + 2 remainder 1 = 1 }

Modulus operator - note that in a batch script, (as opposed to on the


command-line), you need to double up the % to %%
SET /A will treat any character string in the expression as an
environment variable name. This allows you to do arithmetic with
environment variable values without having to type any % signs to get the
values. SET /A _result=5 + _MyVar
Leading Zero will specify Octal

Numeric values are decimal numbers, unless prefixed by


0x for hexadecimal numbers,
0 for octal numbers.

So 0x12 = 022 = 18 decimal

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.

It is also possible (although undocumented) to add permanent env variables to


the registry [HKEY_CURRENT_USER\Environment]
(using REGEDIT)
System Environment variables can also be found in
[HKLM\SYSTEM\CurrentControlSet\Control\Session
Manager\Environment]

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%

::back to Standard commission


ENDLOCAL
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.

A batch file to warn if command extensions are not available:


VERIFY errors 2>nul
SETLOCAL ENABLEEXTENSIONS
IF ERRORLEVEL 1 echo Unable to enable extensions

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.exe (Resource Kit, Windows 7)


Set environment variables permanently

SETX can be used to set Environment Variables for the machine or currently
logged on user:
SETX Variable Value

SETX Variable Value -m

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 _mypc to be COMPAQ in the users permanent environment:

SetX _mypc COMPAQ

Delete the variable _mypc in the users permanent environment:

REG delete HKCU\Environment /V _mypc

Set the variable _myTimeZone in both the immediate user session and the
permanent environment:

SET _myTimeZone=GMT
SetX _myTimeZone GMT

Store the value of %my_important_var% in a second environment variable.


SetX _mybackupvar %my_important_var%

Sets the value of _mypath to be equal to the value of the %PATH%


environment variable, _mypath will then remain the same even if the PATH
variable changes in the future:
SetX _mypath ~PATH~

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

SFC (Windows XP, Server 2003, Win 7)


System File Checker
Syntax
Sfc [/Scannow] [/Scanonce] [/Scanboot] [/Revert] [/Purgecache] [/Cachesize=x]
Key
/Scannow Scan all protected system files immediately and replace
incorrect versions with correct Microsoft versions.
May require access to the Windows installation source files.

/Scanonce Scan all protected system files one time when you restart your computer.
May require access to the Windows installation source
files when you restart the computer.
The SfcScan DWORD value is set to 2 in the following registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon

/Scanboot Scan all protected system files every time you start your computer.
May require access to the Windows installation source files every
time you start the computer.
The SfcScan DWORD value is set to 1 in the following registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon

/Revert Return scan to the default setting
(do not scan protected files when you start the computer).
The default cache size is not reset when you run this command.

/Purgecache Purge the file cache and scan all protected system files immediately.
May require access to the Windows installation source files.

/Cachesize=x Set the file cache size to x megabytes (MB).
The default size of the cache is 50 MB.
This command requires you to restart the computer, and then run
the /purgecache command to adjust the size of the on-disk cache.
This command sets the SfcQuota DWORD value to x in the following registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon

Under Windows 7, SFC must be run from an elevated command prompt.


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:

List the shares on the machine \Frodo


cscript Share.vbs /L /s Frodo

Create a file share called “scratch” on the local machine:


cscript Share.vbs /c /n scratch /p “c:\my shared files” /t Disk /v “project files”

Delete the share named “scratch” on the machine \Frodo


cscript Share.vbs /d /n scratch /s Frodo

SHORTCUT.exe (NT Server Resource


Kit)
Create a windows shortcut (.LNK file)
Syntax
SHORTCUT [options]

Key
Source options
-t target : The path and file name of the application/document to open.
-a arguments : The arguments passed when the shortcut is used.

-d directory : The folder to start the application in.


-i iconfile : The file the icon is in.
-x index : The index into the icon file.

options for the shortcut file to be created

-n name : The path and file name (.LNK) of the shortcut file.
-c : Change existing shortcut.
-r : Resolve broken shortcut.
-f : Force overwrite of an existing short cut.
-s : Make shortcut simple (don’t use LinkResolve)

Export options
-u [spec] : ECHO the contents of an existing shortcut.
‘all’ is the same as ‘natdix’ but the letters
of ‘natdix’ specify the options to be exported

(the same option can be specified more than once

e.g. -u natn)
-l logfile : Save any error messages in the specified file

If shortcut.exe fails to create a new shortcut, it does NOT set an


errorlevel.

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”

‘ oLink.IconLocation = “C:\Program Files\MyApp\MyProgram.EXE, 2”


‘ oLink.WindowStyle = “1”

‘ oLink.WorkingDirectory = “C:\Program Files\MyApp”


oLink.Save

Shortcut: NTFS file system tracking

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

Shortcut: Auto LinkResolve


By default shortcuts will include the destination machine, even for a
target like C:\MyFile.doc
This is not immediately visible until the shortcut.LNK file is copied to
another machine, the shortcut target will then be automatically updated to
point back to \Machine1\c$\MyFile.doc
To turn this behaviour off use shortcut.exe -s or add a DWORD value of 1 to
the registry (before creating the shortcut):

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

If no username is specified SHOWGRPS will list the workgroups for the


currently logged in user.
Example

SHOWGRPS exampledomain\user05

SHOWMBRS (*)
List all the users who are members of a Workgroup.
Syntax
SHOWMBRS domain\Workgroup


SHOWMBRS Workgroup

A workgroup must be specified.

Example:

SHOWMBRS wg_finance

HUTDOWN.exe (for Terminal Services


use: TsShutDn)
Shutdown the computer
Syntax
SHUTDOWN [logoff_option] [/m \Computer] [options]

logoff_options:
/i Display the GUI (must be the first option)
/l Log off. This cannot be used with /m or /d option
/s Shutdown
/r Shutdown and Restart
/a Abort a system shutdown.
(only during the time-out period)
/p Turn off the local computer with no time-out or warning
(only with /d)
/h Hibernate the local computer (only with /f )
/e Document the reason for an unexpected shutdown of a computer

Options:


/m \Computer : A remote computer to shutdown.

/t:xxx : Time until system shutdown in seconds.
The valid range is xxx=0-600 seconds. [default=30]
/c “Msg“ : An optional shutdown message [Max 127 chars]

/f : Force running applications to close.
This will not prompt for File-Save in any open applications.
so will result in a loss of all unsaved data!!!

/d u:xx:yy : List a USER (unplanned) reason code for the shutdown.
/d P:xx:yy : List a PLANNED reason code for the shutdown.
xx Specifies the major reason code (0-255)
yy Specifies the minor reason code (0-65536)

Options in bold are for Windows 2003 and later

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:

e.g. for a delay of 30 seconds:


PING -n 31 127.0.0.1>nul
See Clay Calvert’s newsgroup posting for a full explanation of this
technique.

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

Remove an installed token-based activation issuance license.



/stao Set the Token-based Activation Only flag, disabling automatic KMS activation.
/ctao Clear the Token-based Activation Only flag (default), enabling automatic KMS activation.
/ltc List valid token-based activation certificates that can activate installed software.
/fta Certificate Thumbprint [PIN]
Force token-based activation using the identified certificate.
The optional personal identification number (PIN) is provided to unlock the private
key without a PIN prompt when using certificates that are protected by hardware
(for example, smart cards).

All actions (other than displaying status) require elevated administrator


privileges.
Slmgr.vbs script is not intended to work across platforms i.e. between Vista
and Windows 7

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

SOON schedules jobs to run at a time relative to the current time in


“seconds from now”
It is otherwise identical to the AT command but saves calculating an exact
start time.
As with all AT jobs you should test your SOON scripts by using the
/INTERACTIVE option.
In many cases SCHTASKS may be a better option.

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.

Redirecting a file into SORT

SORT < pathname

Piping a command into SORT

command | SORT

Piping the output from SORT into a file

command | SORT > pathname2


SORT < pathname > pathname2

Piping the output from SORT and appending to an existing file

command | SORT >> pathname2


SORT < pathname >> pathname2

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

Setting a Working Directory


To start an application and specify where files will be saved:

START /Dc:\Documents\ /MAX “Maximised Notes” notepad.exe

Forcing a Sequence of Programs


If you require your users to run a sequence of 32 bit GUI programs to
complete a task, create a batch file that uses the start command:

@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

An alternative method is to run a .BAT batch file under command.com (16


bit)

If Command Extensions are disabled, the START command will no longer


recognise file Associations, and will not automatically evaluate the
COMSPEC variable when starting a second CMD session.

Missing file extensions


When executing a command line whose first token does NOT contain an
extension, then CMD.EXE uses the value of the PATHEXT environment
variable to determine which extensions to look for and in what order. The
default value for the PATHEXT variable is:

.COM;.EXE;.BAT;.CMD

Notice the syntax is the same as the PATH variable, with semicolons
separating the different elements.

When executing a command, if there is no match on any extension, then


Windows will look to see if the name, without any extension, matches a
directory name and if it does, the START command will launch Explorer on
that path.

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

All LogOn Types require specific User Rights to be granted…


SeNetworkLogonRight, SeServiceLogonRight, SeInteractiveLogonRight,
SeBatchLogonRight
The RUNAS command is a lot easier to use!

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.

When running subinacl against a subfolder, its important to include the


trailing backslash, (or \*.*) if they are missed out subinacl may interpret the
path as a filename and search the entire drive for it, this can be very slow.
(This is the opposite behaviour of Robocopy but you didn’t expect
consistency did you! )
Examples:

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

The output includes OS configuration, security info, product ID, RAM,


disk space, and network cards.
Examples
SYSTEMINFO
SYSTEMINFO |find “Total Physical Memory:”
SYSTEMINFO /S wkstn6324
SYSTEMINFO /S wkstn6325 /FO CSV /NH >>pcaudit.csv

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 /v /fi “STATUS eq running”


List the services running under a specific user account:

TASKLIST /v /fi “username eq SERVICE_ACCT05”



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.

To display the time including Seconds:

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:

The time separator can be read using REG as follows


@echo off
FOR /F “TOKENS=3” %%D IN (‘REG QUERY ^“HKEY_CURRENT_USER\Control
Panel\International^” /v sTime ^| find ^“REG_SZ^”’) DO (
SET _time_sep=%%D)
echo %_time_sep%

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

If Command Extensions are disabled TIME will not support the /T


switch

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)

Timeout will pause command execution for a number of seconds, after


which it continues without requiring a user keystroke. If the user does press a
key at any point, execution will resume immediately.
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:

e.g. for a delay of 40 seconds:


PING -n 41 127.0.0.1>nul

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

If MyBatchFile.cmd contains a different TITLE command it will revert


when the second command session ends.
The START command, used to start a program in a separate window also
has an option to specify a title for the new Window.

TLIST (Resource Kit & Windows 2000


support tools)
Task List.

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”

TOUCH (Windows 2000 Resource Kit)


Change file timestamps
Syntax
TOUCH [option]… files …

Key
/t year month day hour minute second

This is a POSIX utility.

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.

The functionality of TRACERT is the same under all versions of


windows but the output is cosmetically improved under XP.
Tracert uses the IP TTL field and ICMP error messages to determine the
route from one host to another through a network.
Care must be taken with tracert as it shows the optimal route, not
necessarily the actual route. To be accurate, it is possible to ping from a
UNIX machine back to the PC using the -R option to record the route taken -
but only if the particular network devices support it.
This diagnostic tool determines the path taken to a destination by
sending ICMP Echo Request messages with varying Time to Live (TTL)
values to the destination.
TTL (Time to Live) calculation
TTL is effectively a count of the (maximum) number of links to the
destination host. Each router along the path decrements the TTL in an IP
packet by at least 1 before forwarding it.
When the TTL on a packet reaches 0, the router is expected to return an
ICMP Time Exceeded message to the source computer.
Tracert determines the path by sending the first Echo Request message
with a TTL of 1 and incrementing the TTL by 1 on each subsequent
transmission until either the target host responds or the maximum number of
hops is reached.
This process relys on intermediate routers to return ICMP Time Exceeded
messages. However, some routers do not return Time Exceeded messages for
packets with expired TTL values and are invisible to the tracert command. In
this case, a row of asterisks (*) is displayed for that hop.
Firewalls
Many firewalls will block ICMP traffic by default. If an attacker is able to
forge ICMP redirect packets, he or she can alter the routing tables on the host
and possibly subvert the security of the host by causing traffic to flow via a
path you didn’t intend.

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.

You must have administrative privileges run tsshutdn.


Using Start Menu | ShutDown is not recommended for shutting down a
terminal server as that method does not notify users before ending their
sessions.
All connected sessions are notified. Sessions that have applications with
open files will prompt the user to save the files. After initiating the logoff
command, tsshutdn waits a specified interval, before ending all processes.
Tsshutdn does not reboot the terminal server unless the /reboot option is
specified.
Examples
End all client sessions 60 seconds after notification, and then 30 seconds
after all the users are logged off, shutdown the current terminal server:

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.

Output can be redirected into a new file:

TYPE file.txt > Newfile.txt

Output can be appended to an existing file:

TYPE file.txt >> ExistingFile.txt

To do the same with user console input :

TYPE CON > Newfile.txt


This will require typing a CTRL-Z to indicate the end of file.

When using redirection to SORT a file the TYPE command is used implicitly
For example:

SORT < MyFile.txt


Create an empty (zero byte) file:
TYPE nul >filename.log
If you TYPE a Unicode text file, the output will be Ascii
(Windows1252). This behaviour is more a limitation of the CMD shell than a
designed feature, any extended characters will be discarded. To work with
Unicode files use PowerShell.
eg:
TYPE UnicodeFile.txt > Ascii.txt

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.

Counter is the full name of a performance counter in the


format:”\Computer\Object(Instance)\Counter”
e.g. “\Server1\Processor(0)\% User Time”.
Examples
Display % Processor time until interrupted:
C:\> typeperf “\Processor(_Total)\% Processor Time”
Gather 600 samples of % Processor time on the local computer (this will
take 10 minutes):
C:\> typeperf “\processor(_Total)\% Processor Time” -O
C:\EXAMPLEdemo1.csv -SC 600
Gather samples of all the counters listed in counters.txt :
C:\> typeperf -cf counters.txt -si 5 -sc 50 -o C:\EXAMPLEdemo2.csv

VER
Display the current operating system version.
Syntax

VER

Use ver to find specific operating systems like this:


@Echo off
Setlocal
:: Get windows Version numbers
For /f “tokens=2 delims=[]” %%G in (‘ver’) Do (set _version=%%G)

For /f “tokens=2,3,4 delims=. ” %%G in (‘echo %_version%’) Do (set _major=%%G& set
_minor=%%H& set _build=%%I)

Echo Major version: %_major% Minor Version: %_minor%.%_build%

if “%_major%”==“5” goto sub5
if “%_major%”==“6” goto sub6

Echo unsupported version
goto:eof

:sub5
::21st Century Windows Releases or 2003
if “%_minor%”==“2” goto sub_2003
Echo Windows XP [%PROCESSOR_ARCHITECTURE%]
goto:eof

:sub_2003
Echo Windows 2003 or XP 64 bit [%PROCESSOR_ARCHITECTURE%]
goto:eof

:sub6
if “%_minor%”==“1” goto sub7
Echo Windows Vista or Windows 2008 [%PROCESSOR_ARCHITECTURE%]
goto:eof

:sub7
Echo Windows 7 or Windows 2008 R2 [%PROCESSOR_ARCHITECTURE%]
goto:eof

Service Pack Version


This Batch script will give the Service Pack level.
Works for NT, Win2K or 21st Century Windows Releases

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]

By default the CMD shell has verify OFF


Windows Explorer will always copy with verify ON

Copying files can be up to twice as fast with verify OFF.

VERIFY without a parameter will display the current setting.

“VERIFY dummy_text” will set %ERRORLEVEL% to 1

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.

WAITFOR.exe (2003 Resource Kit,


standard in Windows 7/2008)
Wait for or send a signal. Waitfor is used to synchronize events between
one or more networked computers.
Syntax
Wait for a signal:

waitfor [/t Timeout] SignalName

Send a signal:
waitfor [/s Computer [/u [Domain\]User [/p [Password]]]] /si SignalName

Key
/s Computer The name or IP address of the computer to signal
(do not include backslashes).

/u User Run the script using the credentials of the specified user account.
By default, waitfor uses the current user’s credentials.

/p [Password] The password of the user account specified with /u

/si Send the signal across the network to waiting machines.

/t Timeout Number of seconds to wait for a signal.
The valid range is 1 - 99999 (27.7 hours)
default = wait indefinitely.

SignalName The signal that waitfor waits for or sends.
SignalName is not case-sensitive.

/? Display help.

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

WHERE (2K Resource Kit / Windows


2003)
Locate and display files in a directory tree.

The WHERE command is roughly equivalent to the UNIX ‘which’ command.


By default, the search is done in the current directory and in the PATH.
Syntax
WHERE [/r Dir] [/q] [/f] [/t] Pattern …

key
/r A recursive search, starting with the specified Dir directory.

/q Don’t display the files but return either an exit code of 0 for success
or 1 for failure.

/f Display the output file name in quotation marks.

/t Display the size, time stamp, and date stamp of the file.

/e Report the executable type.

pattern The name of a folder, file, or set of files to be found.
you can use wildcard characters ( ? * ) and UNC paths.

As an alternative to this command you can use this 90-character batch


file:
@for %%e in (%PATHEXT%) do @for %%i in (%1%%e) do @if NOT “%%~$PATH:i”==””
echo %%~$PATH:i

(from the OldNewthing blog)


Examples
Find all files named ‘CookieMonster’ in drive C: (including
subdirectories)
WHERE /r c:\ CookieMonster

Find all files named ‘CookieMonster’ on the remote computer ‘Server1’


searching its subdirectories, and reporting the executable type for executable
files

WHERE /r \Server1\Share1 /e CookieMonster.*


WHOAMI.exe (*)
Displays the username and domain for the currently logged in user.

The whoami output is the same as the 2 environment variables


%USERDOMAIN% and %USERNAME%.

So the same output can usually be achieved with

ECHO %USERDOMAIN%\%USERNAME%
One exception to this is when using RUNAS /env , e.g. if my username
is Simon:

c:>RunAs /env /user:JDoe cmd.exe


c:>ECHO %USERDOMAIN%\%USERNAME%
example\Simon

c:>whoami
example\JDoe
WHOAMI /all - shows all permissions and group memberships.

WinDiff (Windows SDK)


Compare the contents of two files or sets of files with a graphical
interface.
Syntax
windiff [path1] [path2]

Key
path Individual files to compare
or a directory of files to compare

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

The output is very similar to WINMSD if a little more detailed.

The output will appear in a text file called msdrpt.TXT

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

To terminate the remote command press Ctrl-C or Ctrl-Break, which will


be sent to the remote shell. The second Ctrl-C will force termination of
winrs.exe.
The URI alias to manage active shells is shell/cmd. The URI alias for WinRS
configuration is winrm/config/winrs.
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
Batch file to quickly open a remote cmd shell:
[rshell.cmd]
@echo off
winrs -r:%1 cmd
Run a dir command on a remote machine:
C:\> winrs -r:DemoServer3 dir
Run an install package on a remote server:
C:\> winrs -r:Server25 msiexec.exe /i c:\install.msi /quiet
Run a powershell script on the remote box:
C:\> winrs /r:DemoServer2 powershell.exe -nologo -noprofile -command d:\test\test.ps1

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 /?

The order of the /FORMAT and /TRANSLATE switches is significant: if


/TRANSLATE follows /FORMAT, the output is formatted first and then
translated.
All the options above can be extended with a WHERE clause, best
shown by the examples below:
Format:

Format defines the layout of the information, XML output is


automatically formatted using a default style sheet, while other formats
(HTML, Table, MOF, Raw XML etc) can be specified using /FORMAT:
stylesheet_name
Stylesheets supplied with WMIC:
csv.xsl, hform.xsl, htable-sortby.xsl, htable.xsl

texttable.xsl, textvaluelist.xsl, xml.xsl

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.

WSUS uses a cookie on client computers to store computer group


membership when client-side targeting is used. By default this cookie expires
an hour after WSUS creates it. If you are using client-side targeting and
change group membership, use /ResetAuthorization /detectnow to expire the
cookie, initiate detection, and have WSUS update computer group
membership.
Examples:
C:\> wuauclt /a /DetectNow
C:\> wuauclt /r /DetectNow

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 is a permission applied to a folder. If FolderSpec is not


specified then permission will apply to both files and folders.
This allows you to set different permissions that will apply (through
inheritance) when new files are added to the folder.

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:

(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)
When xcacls is applied to the current folder only there is no inheritance
and so no output.
Versions:
NTFS standards have changed with different versions of Windows and
XCACLS has been updated to suit, early versions of Xcacls may give
unpredictable results against an NTFS v5 partition.
xcacls.vbs is described in Q825751 and can be downloaded here -
xcacls.vbs is an unsupported utility that addresses a limitation with the
original xcacls.exe, specifically the inability to append permissions to a folder
whose child objects have the inheritance flag set. The .vbs version does not
support unc paths and is very slow to update multiple ACLs.
Examples:

:: Allow guests the right to read and execute in MyFolder


XCACLS MyFolder /E /G guests:rx

:: 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

XCOPY is particularly useful when copying files from CDROM to a hard


drive, as it will automatically remove the read-only attribute.
Syntax
XCOPY source [destination] [options]


Key
source : Pathname for the file(s) to be copied.

destination : Pathname for the new file(s).


[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).

XCOPY will accept UNC pathnames

Examples:
To copy a file:

XCOPY C:\utils\MyFile D:\Backup\CopyFile

To copy a folder:

XCOPY C:\utils D:\Backup\utils /i

To copy a folder including all subfolders.

XCOPY C:\utils\* D:\Backup\utils /s /i

The /i defines the destination as a folder.

Notes

In many cases the functionality of XCOPY is superseded by ROBOCOPY.

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).

When comparing Dates/Times the granularity (the finest increment of the


timestamp) is 2 seconds for a FAT volume and 0.1 microsecond for an NTFS
volume.
The 21st Century Windows Releases version of XCOPY will accept
wildcards for the source e.g. *.txt
It is also more forgiving with trailing backslashes

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>


ADDUSERS Add or list users to/from a CSV file

ADMODCMD Active Directory Bulk Modify

ARP Address Resolution Protocol

ASSOC Change file extension associations•

ASSOCIAT One step file association

ATTRIB Change file attributes

BCDBOOT Create or repair a system partition

BITSADMIN Background Intelligent Transfer Service

BOOTCFG Edit Windows boot settings

BROWSTAT Get domain, browser and PDC info

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

DATE Display or set the date•

DEFRAG Defragment hard drive

DEL Delete one or more files•

DELPROF Delete 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

DISKPART Disk Administration

DISKSHADOW Volume Shadow Copy Service

DNSSTAT DNS Statistics

DOSKEY Edit command line, recall commands, and


create macros

DRIVERQUERY Display installed device drivers

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

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

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 File extension file type associations•


GETMAC Display the Media Access Control (MAC)
address

GLOBAL Display membership of global groups

GOTO Direct a batch program to jump to a labelled


line•

GPRESULT Display Resultant Set of Policy information

GPUPDATE Update Group Policy settings

HELP Online Help

ICACLS Change file and folder permissions

IF Conditionally perform a command•

IFMEMBER Is the current user a member of a Workgroup

IPCONFIG Configure IP

KILL Remove a program from memory

LABEL Edit a disk label

LOCAL Display membership of local groups

LOGEVENT Write text to the event viewer

LOGMAN Manage Performance Monitor

LOGOFF Log a user off

LOGTIME Log the date and time in a file

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

MSINFO32 System Information

MSTSC Terminal Server Connection (Remote


Desktop Protocol)

MV Copy in-use files

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

OPENFILES Query or display open files

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 Return to a previous 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•

QGREP Search file(s) for lines that match a given


pattern

QUERY Display processes (TS/Remote Desktop)


PROCESS

QUERY Display all sessions (TS/Remote Desktop)


SESSION

QUERY List all servers (TS/Remote Desktop)


TERMSERVER

QUERY USER Display user sessions (TS/Remote Desktop)

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)

SC Service Control

SCHTASKS Schedule a command to run at a specific time

SCLIST Display Services

SET Display, set, or remove session environment


variables•
SETLOCAL Control the visibility of environment
variables•

SETX Set environment variables

SFC System File Checker

SHARE List or edit a file share or print share

SHELLRUNAS Run a command under a different user


account

SHIFT Shift the position of batch file parameters•

SHORTCUT Create a windows shortcut (.LNK file)

SHOWGRPS List the 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, command or batch file•

SU Switch User

SUBINACL Edit file and folder Permissions, Ownership


and Domain

SUBST Associate a path with a drive letter


SYSTEMINFO List system configuration

TAKEOWN Take ownership of a file

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

USRSTAT List domain usernames and last login

VER Display version information•

VERIFY Verify that files have been saved•

VOL Display a disk label•

WAITFOR Wait for or send a signal

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

WINMSDP Windows system report

WINRM Windows Remote Management

WINRS Windows Remote Shell

WMIC WMI Commands

WUAUCLT Windows Update

XCACLS Change file and folder permissions

XCOPY Copy files and folders

:: 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…

Microsoft Windows shortcuts


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.

Introduced in Windows XP Media Center Edition


Wi n + Al t +↵ Enter to start Windows Media Center interface.
Introduced in Windows Vista
Wi n + G to select next Windows Sidebar gadget item and bring
all gadgets to the foreground.
Wi n + SPACEBA R to show the Windows Sidebar. Replaced with
Aero Peek in Windows 7, as the Windows Sidebar was
discontinued.
Wi n + X to enter the Windows Mobility Center. Works only if
portable computer features are installed.
Wi n + Tab ⇆ to switch windows using Aero Flip 3D. Requires
desktop composition, a feature of Aero.
Wi n + CTR L + Tab ⇆ to switch windows using sticky Aero Flip
3D. Shortcut keys may be released and arrow keys or mouse used to
navigate between windows.
Wi n + 1 , Wi n + 2 , … Wi n + 0 to start the corresponding
Quicklaunch program. Wi n + 0 runs the tenth item. Replaced in
Windows 7, as the Quicklaunch feature was discontinued.
Introduced in Windows 7
Wi n + SPACEBA R to activate Aero Peek. Replaced a previous
shortcut introduced in Windows Vista.
Wi n + P to open the display and projector toggle (to switch
between projection modes when multiple monitors are present).
Monitors can be cloned, “extended” from the primary monitor, or
deactivated altogether.
Wi n + ↑ to maximize the active window.
Wi n + ↓ to restore (default window size, not maximized nor in
taskbar) the active window.
Win + ← or → to align the window to the respective side of the
screen, maximizing it vertically.
Wi n +⇧ Shift + ← or → to move the window to the next or
previous monitor, if multiple monitors are used
Wi n + T to iterate through items on the taskbar.
Wi n + + or Wi n to zoom into the screen at the mouse cursor
position using the Magnifier Utility.
Wi n + - to zoom out if the Magnifier Utility is running.
Wi n + es c to cancel magnification and close the Magnifier Utility.
Wi n + 1 , Wi n + 2 , … Wi n + 0 to run or activate the
corresponding programs in the taskbar. Wi n + 0 runs the tenth
item. Replaced the Quicklaunch shortcuts introduced in Windows
Vista.
Third-party programs may introduce other shortcuts using the Windows
key. For example, OneNote by Microsoft adds several shortcuts:
Wi n + S to take a screenshot for OneNote.
Wi n + N to open a new side note in OneNote.
Wi n +⇧ Shift + N to open OneNote.

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

Accessibility Controls access.cpl

Accessibility Wizard accwiz


Add Hardware Wizard hdwwiz.cpl

Add/Remove Programs appwiz.cpl

Administrative Tools control


admintools

Adobe Acrobat (if installed) acrobat

Adobe Designer (if installed) formdesigner

Adobe Distiller (if installed) acrodist

Adobe ImageReady (if installed) imageready

Adobe Photoshop (if installed) photoshop

Automatic Updates wuaucpl.cpl

Bluetooth Transfer Wizard fsquirt

Calculator calc

Certificate Manager certmgr.msc

Character Map charmap

Check Disk Utility chkdsk

Clipboard Viewer clipbrd

Command Prompt cmd

Component Services dcomcnfg

Computer Management compmgmt.msc

Control Panel control

Date and Time Properties timedate.cpl

DDE Shares ddeshare


Device Manager devmgmt.msc

Direct X Control Panel (if installed)* directx.cpl

Direct X Troubleshooter dxdiag

Disk Cleanup Utility cleanmgr

Disk Defragment dfrg.msc

Disk Management diskmgmt.msc

Disk Partition Manager diskpart

Display Properties control desktop

Display Properties desk.cpl

Display Properties (w/Appearance Tab control color


Preselected)

Dr. Watson System Troubleshooting Utility drwtsn32

Driver Verifier Utility verifier

Event Viewer eventvwr.msc

Files and Settings Transfer Tool migwiz

File Signature Verification Tool sigverif

Findfast findfast.cpl

Firefox (if installed) firefox

Folders Properties folders

Fonts control fonts

Fonts Folder fonts


Free Cell Card Game freecell

Game Controllers joy.cpl

Group Policy Editor (XP Prof) gpedit.msc

Hearts Card Game mshearts

Help and Support helpctr

HyperTerminal hypertrm

Iexpress Wizard iexpress

Indexing Service ciadv.msc

Internet Connection Wizard icwconn1

Internet Explorer iexplore

Internet Properties inetcpl.cpl

Internet Setup Wizard inetwiz

IP Configuration (Display Connection ipconfig /all


Configuration)

IP Configuration (Display DNS Cache ipconfig


Contents) /displaydns

IP Configuration (Delete DNS Cache ipconfig


Contents) /flushdns

IP Configuration (Release All Connections) ipconfig


/release

IP Configuration (Renew All Connections) ipconfig /renew

IP Configuration (Refreshes DHCP & Re- ipconfig


Registers DNS) /registerdns

IP Configuration (Display DHCP Class ID) ipconfig


/showclassid

IP Configuration (Modifies DHCP Class ID) ipconfig


/setclassid

Java Control Panel (if installed) jpicpl32.cpl

Java Control Panel (if installed) javaws

Keyboard Properties control


keyboard

Local Security Settings secpol.msc

Local Users and Groups lusrmgr.msc

Logs You Out Of Windows logoff

Malicious Software Removal Tool mrt

Microsoft Access (if installed) msaccess

Microsoft Chat winchat

Microsoft Excel (if installed) excel

Microsoft Frontpage (if installed) frontpg

Microsoft Movie Maker moviemk

Microsoft Paint mspaint

Microsoft Powerpoint (if installed) powerpnt

Microsoft Word (if installed) winword

Microsoft Syncronization Tool mobsync

Minesweeper Game winmine

Mouse Properties control mouse


Mouse Properties main.cpl

Nero (if installed) nero

Netmeeting conf

Network Connections control


netconnections

Network Connections ncpa.cpl

Network Setup Wizard netsetup.cpl

Notepad notepad

Nview Desktop Manager (if installed) nvtuicpl.cpl

Object Packager packager

ODBC Data Source Administrator odbccp32.cpl

On Screen Keyboard osk

Opens AC3 Filter (if installed) ac3filter.cpl

Outlook Express msimn

Paint pbrush

Password Properties password.cpl

Performance Monitor perfmon.msc

Performance Monitor perfmon

Phone and Modem Options telephon.cpl

Phone Dialer dialer

Pinball Game pinball


Power Configuration powercfg.cpl

Printers and Faxes control printers

Printers Folder printers

Private Character Editor eudcedit

Quicktime (If Installed) QuickTime.cpl

Quicktime Player (if installed) quicktimeplayer

Real Player (if installed) realplay

Regional Settings intl.cpl

Registry Editor regedit

Registry Editor regedit32

Remote Access Phonebook rasphone

Remote Desktop mstsc

Removable Storage ntmsmgr.msc

Removable Storage Operator Requests ntmsoprq.msc

Resultant Set of Policy (XP Prof) rsop.msc

Scanners and Cameras sticpl.cpl

Scheduled Tasks control


schedtasks

Security Center wscui.cpl

Services services.msc

Shared Folders fsmgmt.msc

Shuts Down Windows shutdown


Sounds and Audio mmsys.cpl

Spider Solitaire Card Game spider

SQL Client Configuration cliconfg

System Configuration Editor sysedit

System Configuration Utility msconfig

System File Checker Utility (Scan sfc /scannow


Immediately)

System File Checker Utility (Scan Once At sfc /scanonce


The Next Boot)

System File Checker Utility (Scan On Every sfc /scanboot


Boot)

System File Checker Utility (Return Scan sfc /revert


Setting To Default)

System File Checker Utility (Purge File sfc /purgecache


Cache)

System File Checker Utility (Sets Cache Size sfc


to size x) /cachesize=x

System Information msinfo32

System Properties sysdm.cpl

Task Manager taskmgr

TCP Tester tcptest

Telnet Client telnet

Tweak UI (if installed) tweakui

User Account Management nusrmgr.cpl


Utility Manager utilman

Windows Address Book wab

Windows Address Book Import Utility wabmig

Windows Backup Utility (if installed) ntbackup

Windows Explorer explorer

Windows Firewall firewall.cpl

Windows Magnifier magnify

Windows Management Infrastructure wmimgmt.msc

Windows Media Player wmplayer

Windows Messenger msmsgs

Windows Picture Import Wizard (need wiaacmgr


camera connected)

Windows System Security Tool syskey

Windows Update Launches wupdmgr

Windows Version (to show which version of winver


windows)

Windows XP Tour Wizard tourstart

Wordpad write









POWERSHELL COMMAND
TRANSLATION

OPERATION CMD POWERSHELL

Get a simple dir get-childitem


directory listing
alias: dir

Get a recursive dir /s get-childitem -recurse


directory listing
alias: dir -r

Get a wide dir /w dir | format-wide


directory list
alias: dir | fw

List built-in help get-command


commands
alias: help

Copy a file copy foo.txt bar.txt copy-item foo.txt bar.txt


alias: copy foo.txt bar.txt

Move a file move foo.txt c:\ move-item foo.txt d:\


alias: move foo.txt d:\

Rename a file ren foo.txt bar.txt rename-item foo.txt bar.txt


alias: ren foo.txt bar.txt

Batch rename ren *.one *.two dir *.pdf | rename


-newname {$_.name -rep
“.one”,”.two”}

Set the current d: set-location d:\


directory to d:\
cd \ alias: cd d:\

Clear the screen cls clear-host


alias: cls

List only dir /ad dir | where { $_.MshIsContainer }


directories
Directory list, dir /od dir | sort-object LastWriteTime
sorted by date

Directory list, dir /o-d dir | sort-object LastWriteTime -


sorted by date, desc
descending order

Show the current cd get-location


directory
alias: pwd

See a command’s dir /? get-help get-command


help
or: get-help get-command -detailed
or: get-help get-command -full
or: dir -?

List environment set dir env:


variables

Delete a file del foo.txt remove-item foo.txt


alias: del foo.txt

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

Show a list of net start get-service


services

Start a service net start MyService start-service MyService

Stop a service net stop MyService stop-service MyService

Show network net share gwmi Win32_Share


shares

Show a list of tasklist get-process alias: ps


running processes

Kill all taskkill /im ps notepad | kill


notepad.exe processes notepad.exe /f

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

Get a list of event logs get-eventlog -list

View entries in a particular event get-eventlog -newest 20 -


log logname System

cd hkcu:
Treat the registry like a filesystem
dir

Recursive directory, grouped by


dir -r | group extension
extension

Search for a file containing a


dir -r | select-string “foo”
string, recursive

List the 10 processes using the


ps | sort -p ws | select -last 10
most memory

Count the results of a directory


(dir).count
listing

$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:

Command Name Description

Add-BitsFile Adds one or more files to an


existing Background Intelligent
Transfer Service (BITS)
transfer job.

Add-Computer Add the local computer to a


domain or workgroup.

Add-Content Adds content to the specified


items, such as adding words to
a file.

Add-History Appends entries to the session


history.

Add-JobTrigger Adds job triggers to scheduled


jobs

Add-Member Adds custom properties and


methods to an instance of a
Windows PowerShell object.

Add-PSSnapin Adds one or more Windows


PowerShell snap-ins to the
current session.

Add-Type Adds a Microsoft .NET


Framework type (a class) to a
Windows PowerShell session.

Checkpoint-Computer Creates a system restore point


on the local computer.

Clear-Content Deletes the contents of an item,


but does not delete the item.

Clear-EventLog Clears all entries from


specified event logs on the
local or remote computers.

Clear-History Deletes entries from the


command history.
Clear-Item Clears the contents of an item,
but does not delete the item.

Clear-ItemProperty Clears the value of a property


but does not delete the
property.

Clear-Recyclebin

Clear-Variable Deletes the value of a variable.

Compare-Object Compares two sets of objects.

Complete-BitsTransfer Completes a Background


Intelligent Transfer Service
(BITS) transfer job.

Complete-Transaction Commits the active transaction.

Compress-Archive Creates a new archive, or


zipped file, from specified files
and folders.

Configuration

Connect-PSSession Reconnects to disconnected


sessions

Connect-WSMan Connects to the WinRM


service on a remote computer.

Convert-Path Converts a path from a


Windows PowerShell path to a
Windows PowerShell provider
path.

Convert-String

ConvertFrom-Csv Converts object properties in


comma-separated value (CSV)
format into CSV versions of
the original objects.

ConvertFrom-Json Converts a JSON-formatted


string to a custom object.

ConvertFrom-SddlString

ConvertFrom-SecureString Converts a secure string into an


encrypted standard string.
ConvertFrom-String Extracts and parses structured
objects from string content.

ConvertFrom-StringData Converts a string containing


one or more key and value
pairs to a hash table.

ConvertTo-Csv Converts objects into a series


of comma-separated value
(CSV) variable-length strings.

ConvertTo-Html Converts Microsoft .NET


Framework objects into HTML
that can be displayed in a Web
browser.

ConvertTo-Json Converts an object to a JSON-


formatted string

ConvertTo-SecureString Converts encrypted standard


strings to secure strings. It can
also convert plain text to
secure strings. It is used …

ConvertTo-Xml Creates an XML-based


representation of an object.

Copy-Item Copies an item from one


location to another.

Copy-ItemProperty Copies a property and value


from a specified location to
another location.

Debug-Job Debugs a running background,


remote, or Windows
PowerShell Workflow job.

Debug-Process Debugs one or more processes


running on the local computer.

Debug-Runspace Starts an interactive debugging


session with a runspace.

Disable-ComputerRestore Disables the System Restore


feature on the specified file
system drive.

Disable-DscDebug Stops debugging of DSC


resources.

Disable-JobTrigger Disables the job triggers of


scheduled jobs

Disable-NetworkSwitchEthernetPort Disables an Ethernet port on a


network switch.

Disable-NetworkSwitchFeature Disables features of a network


switch.

Disable-NetworkSwitchVlan Disables a VLAN of a network


switch.

Disable-PSBreakpoint Disables the breakpoints in the


current console.

Disable-PSRemoting Prevents remote users from


running commands on the local
computer.

Disable-PSSessionConfiguration Disables session configurations


on the local computer.

Disable-PSTrace

Disable-PSWSManCombinedTrace

Disable-RunspaceDebug Disables debugging on one or


more runspaces, and releases
any pending debugger stop.

Disable-ScheduledJob Disables a scheduled job

Disable-WSManCredSSP Disables Credential Security


Support Provider (CredSSP)
authentication on a client
computer.

Disable-WSManTrace

Disconnect-PSSession Disconnects from a session.

Disconnect-WSMan Disconnects the client from the


WinRM service on a remote
computer.

Enable-ComputerRestore Enables the System Restore


feature on the specified file
system drive.

Enable-DscDebug Start debugging of all DSC


resources.
Enable-JobTrigger Enables the job triggers of
scheduled jobs

Enable-NetworkSwitchEthernetPort Enables an Ethernet port on a


network switch.

Enable-NetworkSwitchFeature Enables features of a network


switch.

Enable-NetworkSwitchVlan Enables a VLAN for a network


switch.

Enable-PSBreakpoint Enables the breakpoints in the


current console.

Enable-PSRemoting Configures the computer to


receive remote commands.

Enable-PSSessionConfiguration Enables the session


configurations on the local
computer.

Enable-PSTrace

Enable-PSWSManCombinedTrace

Enable-RunspaceDebug Enables debugging on


runspaces where any
breakpoint is preserved until a
debugger is attached.

Enable-ScheduledJob Enables a scheduled job

Enable-WSManCredSSP Enables Credential Security


Support Provider (CredSSP)
authentication on a client or on
a server computer.

Enable-WSManTrace

Enter-PSHostProcess Connects to and enters into an


interactive session with a local
process.

Enter-PSSession Starts an interactive session


with a remote computer.

Exit-PSHostProcess Closes an interactive session


with a local process.

Exit-PSSession Ends an interactive session


with a remote computer.

Expand-Archive Extracts files from a specified


archive (zipped) file.

Export-Alias Exports information about


currently defined aliases to a
file.

Export-BinaryMiLog

Export-Clixml Creates an XML-based


representation of an object or
objects and stores it in a file.

Export-Console Exports the names of snap-ins


in the current session to a
console file.

Export-Counter The Export-Counter cmdlet


takes
PerformanceCounterSampleSet
objects and exports them as
counter log files.

Export-Csv Converts objects into a series


of comma-separated (CSV)
strings and saves the strings in
a CSV file.

Export-FormatData Saves formatting data from the


current session in a formatting
file.

Export-ModuleMember Specifies the module members


that are exported.

Export-ODataEndpointProxy Generates a module that


contains cmdlets to manage an
OData endpoint.

Export-PSSession Imports commands from


another session and saves them
in a Windows PowerShell
module.

Find-DscResource Finds a DSC resource.

Find-Module Finds modules from an online


gallery that match specified
criteria.
Find-Package Finds software packages in
available package sources.

Find-PackageProvider Returns a list of Package


Management package
providers available for
installation.

Find-Script Finds a script.

ForEach-Object Performs an operation against


each item in a collection of
input objects.

Format-Custom Uses a customized view to


format the output.

Format-Hex

Format-List Formats the output as a list of


properties in which each
property appears on a new line.

Format-Table Formats the output as a table.

Format-Wide Formats objects as a wide table


that displays only one property
of each object.

Get-Acl Gets the security descriptor for


a resource, such as a file or
registry key.

Get-Alias Gets the aliases for the current


session.

Get-AppLockerFileInformation Gets the AppLocker file


information from a list of files
or an event log.

Get-AppLockerPolicy Gets the local, effective, or


domain AppLocker policy.

Get-AuthenticodeSignature Gets information about the


Authenticode signature in a
file.

Get-BitsTransfer Retrieves the associated


BitsJob object for an existing
Background Intelligent
Transfer Service (BITS)
transfer job.
Get-ChildItem Gets the items and child items
in one or more specified
locations.

Get-CimAssociatedInstance Retrieves the CIM instances


that are connected to a specific
CIM instance by an
association.

Get-CimClass Gets a list of CIM classes in a


specific namespace.

Get-CimInstance Gets the CIM instances of a


class from a CIM server.

Get-CimSession Gets the CIM session objects


from the current session.

Get-Clipboard Gets the current Windows


clipboard entry.

Get-CmsMessage Gets content that has been


encrypted by using the
Cryptographic Message Syntax
format.

Get-Command Gets all commands.

Get-ComputerRestorePoint Gets the restore points on the


local computer.

Get-Content Gets the content of the item at


the specified location.

Get-ControlPanelItem Gets control panel items.

Get-Counter Gets performance counter data


from local and remote
computers.

Get-Credential Gets a credential object based


on a user name and password.

Get-Culture Gets the current culture set in


the operating system.

Get-Date Gets the current date and time.

Get-DscConfiguration Gets the current configuration


of the nodes.
Get-DscConfigurationStatus Retrieves data about completed
configuration runs.

Get-DscLocalConfigurationManager Gets Local Configuration


Manager settings and states for
the node.

Get-DscResource Gets the DSC resources present


on the computer.

Get-Event Gets the events in the event


queue.

Get-EventLog Gets the events in an event log,


or a list of the event logs, on
the local or remote computers.

Get-EventSubscriber Gets the event subscribers in


the current session.

Get-ExecutionPolicy Gets the execution policies for


the current session.

Get-FileHash

Get-FormatData Gets the formatting data in the


current session.

Get-Help Displays information about


Windows PowerShell
commands and concepts.

Get-History Gets a list of the commands


entered during the current
session.

Get-Host Gets an object that represents


the current host program.

Get-HotFix Gets the hotfixes that have


been applied to the local and
remote computers.

Get-InstalledModule Gets installed modules on a


computer.

Get-InstalledScript Gets an installed script.

Get-IseSnippet
Get-Item Gets the item at the specified
location.

Get-ItemProperty Gets the properties of a


specified item.

Get-ItemPropertyValue Gets the value for one or more


properties of a specified item.

Get-Job Gets Windows PowerShell


background jobs that are
running in the current session.

Get-JobTrigger Gets the job triggers of


scheduled jobs.

Get-Location Gets information about the


current working location or a
location stack.

Get-LogProperties

Get-Member Gets the properties and


methods of objects.

Get-Module Gets the modules that have


been imported or that can be
imported into the current
session.

Get-NetworkSwitchEthernetPort Gets port information for a


network switch.

Get-NetworkSwitchFeature

Get-NetworkSwitchGlobalData Gets global data of a network


switch.

Get-NetworkSwitchVlan Gets VLANs for a network


switch.

Get-PSBreakpoint Gets the breakpoints that are


set in the current session.

Get-PSCallStack Displays the current call stack.

Get-PSDrive Gets drives in the current


session.

Get-PSHostProcessInfo
Get-PSProvider Gets information about the
specified Windows PowerShell
provider.

Get-PSRepository Gets PowerShell repositories.

Get-PSSession Gets the Windows PowerShell


sessions on local and remote
computers.

Get-PSSessionCapability Gets the capabilities of a


specific user on a constrained
session configuration.

Get-PSSessionConfiguration Gets the registered session


configurations on the
computer.

Get-PSSnapin Gets the Windows PowerShell


snap-ins on the computer.

Get-Package Returns a list of all software


packages that have been
installed by using Package
Management.

Get-PackageProvider Returns a list of package


providers that are connected to
Package Management.

Get-PackageSource Gets a list of package sources


that are registered for a
package provider.

Get-PfxCertificate Gets information about .pfx


certificate files on the
computer.

Get-Process Gets the processes that are


running on the local computer
or a remote computer.

Get-Random Gets a random number, or


selects objects randomly from
a collection.

Get-Runspace Gets active runspaces within a


Windows PowerShell host
process.

Get-RunspaceDebug Shows runspace debugging


options.
Get-ScheduledJob Gets scheduled jobs on the
local computer.

Get-ScheduledJobOption Gets the job options of


scheduled jobs.

Get-Service Gets the services on a local or


remote computer.

Get-TraceSource Gets the Windows PowerShell


components that are
instrumented for tracing.

Get-Transaction Gets the current (active)


transaction.

Get-TroubleshootingPack Gets information about a


troubleshooting pack and can
generate an answer file.

Get-TypeData Gets the extended type data in


the current session.

Get-UICulture Gets the current user interface


(UI) culture settings in the
operating system.

Get-Unique Returns unique items from a


sorted list.

Get-Variable Gets the variables in the


current console.

Get-WSManCredSSP Gets the Credential Security


Support Provider-related
configuration for the client.

Get-WSManInstance Displays management


information for a resource
instance specified by a
Resource URI.

Get-WinEvent Gets events from event logs


and event tracing log files on
local and remote computers.

Get-WmiObject Gets instances of WMI classes


or information about the
available classes.

Group-Object Groups objects that contain the


same value for specified
properties.

Import-Alias Imports an alias list from a file.

Import-BinaryMiLog

Import-Clixml Imports a CLIXML file and


creates corresponding objects
within Windows PowerShell.

Import-Counter Imports performance counter


log files (.blg, .csv, .tsv) and
creates the objects that
represent each counter sample

Import-Csv Creates table-like custom


objects from the items in a
CSV file.

Import-IseSnippet

Import-LocalizedData Imports language-specific data


into scripts and functions based
on the UI culture that is
selected for the operating…

Import-Module Adds modules to the current


session.

Import-PSSession Imports commands from


another session into the current
session.

Import-PackageProvider Adds Package Management


package providers to the
current session.

Import-PowerShellDataFile

Install-Module Downloads one or more


modules from an online
gallery, and installs them on
the local computer.

Install-Package Installs one or more software


packages.

Install-PackageProvider Installs one or more Package


Management package
providers.
Install-Script Installs a script.

Invoke-AsWorkflow Runs a command or expression


as a Windows PowerShell
Workflow.

Invoke-CimMethod Invokes a method of a CIM


class.

Invoke-Command Runs commands on local and


remote computers.

Invoke-DscResource Runs a method of a specified


DSC resource.

Invoke-Expression Runs commands or expressions


on the local computer.

Invoke-History Runs commands from the


session history.

Invoke-Item Performs the default action on


the specified item.

Invoke-RestMethod Sends an HTTP or HTTPS


request to a RESTful web
service.

Invoke-TroubleshootingPack Executes a troubleshooting


pack in interactive or
unattended mode to fix a
problem, and then generates a
results rep…

Invoke-WSManAction Invokes an action on the object


that is specified by the
Resource URI and by the
selectors.

Invoke-WebRequest Gets content from a web page


on the Internet.

Invoke-WmiMethod Calls WMI methods.

Join-Path Combines a path and a child


path into a single path.

Limit-EventLog Sets the event log properties


that limit the size of the event
log and the age of its entries.
Measure-Command Measures the time it takes to
run script blocks and cmdlets.

Measure-Object Calculates the numeric


properties of objects, and the
characters, words, and lines in
string objects, such as files …

Move-Item Moves an item from one


location to another.

Move-ItemProperty Moves a property from one


location to another.

New-Alias Creates a new alias.

New-AppLockerPolicy Creates a new AppLocker


policy from a list of file
information and other rule-
creation options.

New-CimInstance Creates a CIM instance.

New-CimSession Creates a CIM session.

New-CimSessionOption Specifies advanced options for


the New-CimSession cmdlet.

New-DscChecksum Creates checksum files for


Desired State Configuration
documents and Desired State
Configuration resources.

New-Event Creates a new event.

New-EventLog Creates a new event log and a


new event source on a local or
remote computer.

New-Guid

New-IseSnippet

New-Item Creates a new item.

New-ItemProperty Creates a new property for an


item and sets its value.

New-JobTrigger Creates a job trigger for a


scheduled job
New-Module Creates a new dynamic module
that exists only in memory.

New-ModuleManifest Creates a new module


manifest.

New-NetworkSwitchVlan Creates a VLAN for a network


switch.

New-Object Creates an instance of a


Microsoft .NET Framework or
COM object.

New-PSDrive Creates temporary and


persistent mapped network
drives.

New-PSRoleCapabilityFile Creates a file that defines a set


of capabilities to be exposed
through a session
configuration.

New-PSSession Creates a persistent connection


to a local or remote computer.

New-PSSessionConfigurationFile Creates a file that defines a


session configuration.

New-PSSessionOption Creates an object that contains


advanced options for a
PSSession.

New-PSTransportOption Creates an object that contains


advanced options for a session
configuration.

New-PSWorkflowExecutionOption Creates an object that contains


session configuration options
for workflow sessions.

New-PSWorkflowSession Creates a workflow session.

New-ScheduledJobOption Creates an object that contains


advanced options for a
scheduled job.

New-ScriptFileInfo Creates a script file with


metadata.

New-Service Creates a new Windows


service.
New-TemporaryFile

New-TimeSpan Creates a TimeSpan object.

New-Variable Creates a new variable.

New-WSManInstance Creates a new instance of a


management resource.

New-WSManSessionOption Creates a WS-Management


session option hash table to use
as input parameters to the
following WS-Management
cmdlets:…

New-WebServiceProxy Creates a Web service proxy


object that lets you use and
manage the Web service in
Windows PowerShell.

New-WinEvent Creates a new Windows event


for the specified event
provider.

Out-Default Sends the output to the default


formatter and to the default
output cmdlet.

Out-File Sends output to a file.

Out-GridView Sends output to an interactive


table in a separate window.

Out-Host Sends output to the command


line.

Out-Null Deletes output instead of


sending it down the pipeline.

Out-Printer Sends output to a printer.

Out-String Sends objects to the host as a


series of strings.

Pop-Location Changes the current location to


the location most recently
pushed onto the stack.

Protect-CmsMessage Encrypts content by using the


Cryptographic Message Syntax
format.
Publish-DscConfiguration Publishes a DSC configuration
to a set of machines, but does
not apply it.

Publish-Module Publishes a specified module


from the local computer to an
online gallery.

Publish-Script Publishes a script.

Push-Location Adds the current location to the


top of a location stack.

Read-Host Reads a line of input from the


console.

Receive-Job Gets the results of the


Windows PowerShell
background jobs in the current
session.

Receive-PSSession Gets results of commands in


disconnected sessions

Register-ArgumentCompleter

Register-CimIndicationEvent Subscribes to indications using


a filter expression or a query
expression.

Register-EngineEvent Subscribes to events that are


generated by the Windows
PowerShell engine and by the
New-Event cmdlet.

Register-ObjectEvent Subscribes to the events that


are generated by a Microsoft
.NET Framework object.

Register-PSRepository Registers a PowerShell


repository.

Register-PSSessionConfiguration Creates and registers a new


session configuration.

Register-PackageSource Adds a package source for a


specified package provider.

Register-ScheduledJob Creates a new scheduled job.


Register-WmiEvent Subscribes to a Windows
Management Instrumentation
(WMI) event.

Remove-BitsTransfer Cancels a Background


Intelligent Transfer Service
(BITS) transfer job.

Remove-CimInstance Removes a CIM instance from


a computer.

Remove-CimSession Removes one or more CIM


sessions.

Remove-Computer Removes the local computer


from its domain.

Remove-DscConfigurationDocument Removes a configuration


document from the DSC
configuration store.

Remove-Event Deletes events from the event


queue.

Remove-EventLog Deletes an event log or


unregisters an event source.

Remove-Item Deletes the specified items.

Remove-ItemProperty Deletes the property and its


value from an item.

Remove-Job Deletes a Windows PowerShell


background job.

Remove-JobTrigger Delete job triggers from


scheduled jobs

Remove-Module Removes modules from the


current session.

Remove- Removes an IP address from a


NetworkSwitchEthernetPortIPAddress port of a network switch.

Remove-NetworkSwitchVlan Removes network switch


VLANs.

Remove-PSBreakpoint Deletes breakpoints from the


current console.

Remove-PSDrive Deletes temporary Windows


PowerShell drives and
disconnects mapped network
drives.

Remove-PSSession Closes one or more Windows


PowerShell sessions
(PSSessions).

Remove-PSSnapin Removes Windows PowerShell


snap-ins from the current
session.

Remove-TypeData Deletes extended types from


the current session

Remove-Variable Deletes a variable and its


value.

Remove-WSManInstance Deletes a management


resource instance.

Remove-WmiObject Deletes an instance of an


existing Windows
Management Instrumentation
(WMI) class.

Rename-Computer Renames a computer.

Rename-Item Renames an item in a Windows


PowerShell provider
namespace.

Rename-ItemProperty Renames a property of an item.

Reset-ComputerMachinePassword Resets the machine account


password for the computer.

Resolve-Path Resolves the wildcard


characters in a path, and
displays the path contents.

Restart-Computer Restarts (“reboots”) the


operating system on local and
remote computers.

Restart-Service Stops and then starts one or


more services.

Restore-Computer Starts a system restore on the


local computer.
Restore-DscConfiguration Reapplies the previous
configuration for the node.

Restore-NetworkSwitchConfiguration Restores configuration for a


network switch.

Resume-BitsTransfer Resumes a Background


Intelligent Transfer Service
(BITS) transfer job.

Resume-Job Restarts a suspended job

Resume-Service Resumes one or more


suspended (paused) services.

Save-Help Downloads and saves the


newest help files to a file
system directory.

Save-Module Saves a module locally without


installing it.

Save-NetworkSwitchConfiguration Saves configuration for starting


a network switch.

Save-Package Saves packages to the local


computer without installing
them.

Save-Script Saves a script.

Select-Object Selects objects or object


properties.

Select-String Finds text in strings and files.

Select-Xml Finds text in an XML string or


document.

Send-MailMessage Sends an e-mail message.

Set-Acl Changes the security descriptor


of a specified item, such as a
file or a registry key.

Set-Alias Creates or changes an alias


(alternate name) for a cmdlet
or other command element in
the current Windows
PowerShell…
Set-AppLockerPolicy Sets the AppLocker policy for
the specified Group Policy
object (GPO).

Set-AuthenticodeSignature Adds an Authenticode


signature to a Windows
PowerShell script or other file.

Set-BitsTransfer Modifies the properties of an


existing Background Intelligent
Transfer Service (BITS)
transfer job.

Set-CimInstance Modifies a CIM instance on a


CIM server by calling the
ModifyInstance method of the
CIM class..

Set-Clipboard Sets the current Windows


clipboard entry.

Set-Content Writes or replaces the content


in an item with new content.

Set-Date Changes the system time on


the computer to a time that you
specify.

Set-DscLocalConfigurationManager Applies Local Configuration


Manager settings to nodes.

Set-ExecutionPolicy Changes the user preference


for the Windows PowerShell
execution policy.

Set-Item Changes the value of an item to


the value specified in the
command.

Set-ItemProperty Creates or changes the value of


a property of an item.

Set-JobTrigger Changes the job trigger of a


scheduled job.

Set-Location Sets the current working


location to a specified location.

Set-LogProperties

Set- Sets the IP address on a port on


NetworkSwitchEthernetPortIPAddress a network switch.
Set-NetworkSwitchPortMode Sets the port mode on a
network switch.

Set-NetworkSwitchPortProperty Sets the port properties for a


network switch.

Set-NetworkSwitchVlanProperty Modifies properties on a


VLAN on a network switch.

Set-PSBreakpoint Sets a breakpoint on a line,


command, or variable.

Set-PSDebug Turns script debugging features


on and off, sets the trace level,
and toggles strict mode.

Set-PSRepository Sets values for a registered


repository.

Set-PSSessionConfiguration Changes the properties of a


registered session
configuration.

Set-PackageSource Replaces a package source for


a specified package provider.

Set-ScheduledJob Changes scheduled jobs

Set-ScheduledJobOption Changes the job options of a


scheduled job.

Set-Service Starts, stops, and suspends a


service, and changes its
properties.

Set-StrictMode Establishes and enforces


coding rules in expressions,
scripts, and script blocks.

Set-TraceSource Configures, starts, and stops a


trace of Windows PowerShell
components.

Set-Variable Sets the value of a variable.


Creates the variable if one with
the requested name does not
exist.

Set-WSManInstance Modifies the management


information that is related to a
resource.
Set-WSManQuickConfig Configures the local computer
for remote management.

Set-WmiInstance Creates or updates an instance


of an existing Windows
Management Instrumentation
(WMI) class.

Show-Command Creates Windows PowerShell


commands in a graphical
command window.

Show-ControlPanelItem Opens control panel items.

Show-EventLog Displays the event logs of the


local or a remote computer in
Event Viewer.

Sort-Object Sorts objects by property


values.

Split-Path Returns the specified part of a


path.

Start-BitsTransfer Creates a new Background


Intelligent Transfer Service
(BITS) transfer job.

Start-DscConfiguration Applies configuration to nodes.

Start-Job Starts a Windows PowerShell


background job.

Start-Process Starts one or more processes


on the local computer.

Start-Service Starts one or more stopped


services.

Start-Sleep Suspends the activity in a


script or session for the
specified period of time.

Start-Trace

Start-Transaction Starts a transaction.

Start-Transcript Creates a record of all or part


of a Windows PowerShell
session in a text file.
Stop-Computer Stops (shuts down) local and
remote computers.

Stop-DscConfiguration Stops a running configuration.

Stop-Job Stops a Windows PowerShell


background job.

Stop-Process Stops one or more running


processes.

Stop-Service Stops one or more running


services.

Stop-Trace

Stop-Transcript Stops a transcript.

Suspend-BitsTransfer Suspends a Background


Intelligent Transfer Service
(BITS) transfer job.

Suspend-Job Temporarily stops workflow


jobs.

Suspend-Service Suspends (pauses) one or more


running services.

Tee-Object Saves command output in a file


or variable and also sends it
down the pipeline.

Test-AppLockerPolicy Tests whether the input files


are allowed to run for a given
user based on the specified
AppLocker policy.

Test-ComputerSecureChannel Tests and repairs the secure


channel between the local
computer and its domain.

Test-Connection Sends ICMP echo request


packets (“pings”) to one or
more computers.

Test-DscConfiguration Tests whether the actual


configuration on the nodes
matches the desired
configuration.
Test-ModuleManifest Verifies that a module manifest
file accurately describes the
contents of a module.

Test-PSSessionConfigurationFile Verifies the keys and values in


a session configuration file.

Test-Path Determines whether all


elements of a path exist.

Test-ScriptFileInfo Validates a comment block for


a script.

Test-WSMan Tests whether the WinRM


service is running on a local or
remote computer.

Trace-Command Configures and starts a trace of


the specified expression or
command.

Unblock-File Unblocks files that were


downloaded from the Internet.

Undo-Transaction Rolls back the active


transaction.

Uninstall-Module Uninstalls a module.

Uninstall-Package Uninstalls one or more


software packages.

Uninstall-Script Uninstalls a script file.

Unprotect-CmsMessage Decrypts content that has been


encrypted by using the
Cryptographic Message Syntax
format.

Unregister-Event Cancels an event subscription.

Unregister-PSRepository Unregisters a repository.

Unregister-PSSessionConfiguration Deletes registered session


configurations from the
computer.

Unregister-PackageSource Removes a registered package


source.

Unregister-ScheduledJob Deletes scheduled jobs on the


local computer.

Update-DscConfiguration Checks the pull server for an


updated configuration and
applies it.

Update-DscConfiguration Checks the pull server for an


updated configuration and
applies it.

Update-FormatData Updates the formatting data in


the current session.

Update-Help Downloads and installs the


newest help files on your
computer.

Update-List Adds items to and removes


items from a property value
that contains a collection of
objects.

Update-Module Downloads and installs the


newest version of specified
modules from an online gallery
to the local computer.

Update-ModuleManifest Updates a module manifest


file.

Update-Script Updates a script.

Update-ScriptFileInfo Updates information for a


script.

Update-TypeData Updates the extended type data


in the session.

Use-Transaction Adds the script block to the


active transaction.

Wait-Debugger Stops a script in the debugger


before running the next
statement in the script.

Wait-Event Waits until a particular event is


raised before continuing to run.

Wait-Job Suppresses the command


prompt until one or all of the
Windows PowerShell
background jobs running in the
session are …

Wait-Process Waits for the processes to be


stopped before accepting more
input.

Where-Object Selects objects from a


collection based on their
property values.

Write-Debug Writes a debug message to the


console.

Write-Error Writes an object to the error


stream.

Write-EventLog Writes an event to an event log.

Write-Host Writes customized output to a


host.

Write-Information Specifies how Windows


PowerShell handles
information stream data for a
command.

Write-Output Sends the specified objects to


the next command in the
pipeline. If the command is the
last command in the pipeline,

Write-Progress Displays a progress bar within


a Windows PowerShell
command window.

Write-Verbose Writes text to the verbose


message stream.

Write-Warning Writes a warning message.


C:\WINDOWS\SYSTEM32> exit

You might also like