By : Ir. Teguh W.
a
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
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
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
DSADD Add user (computer, group..) to active directory
DSQUERY List items in active directory
DSMOD Modify user (computer, group..) in active directory
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
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)
MUNGE Find and Replace text within file(s)
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
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
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
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
TYPE Display the contents of a text 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
WMIC WMI Commands
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.
================================ 0***0 ==================================
QGREP Cari file (s) untuk baris yang cocok dengan pola tertentu.
SC Control Layanan
SCHTASKS Jadwal untuk menjalankan perintah pada waktu tertentu
SCLIST Tampilan NT Layanan
SET Display, set, atau menghapus variabel lingkungan •
SETLOCAL Pengendalian lingkungan visibilitas variabel •
SETX Set variabel lingkungan secara permanen
SFC Sistem File checker
SAHAM Daftar atau mengedit file atau mencetak berbagi berbagi
SHIFT Shift posisi digantikan parameter dalam sebuah file batch
SHORTCUT jendela Buat shortcut (. LNK file) “Pintas”
SHOWGRPS Daftar NT Workgroups seorang pengguna telah bergabung
SHOWMBRS Daftar Pengguna yang menjadi anggota sebuah Workgroup
SHUTDOWN Shutdown komputer
Sleep Tunggu untuk x detik
SLMGR Software Licensing Management (Vista/2008)
SOON Jadwal perintah untuk menjalankan dalam waktu dekat
SORT Sort input
START Start a program atau perintah dalam jendela terpisah •
SU Switch User
SUBINACL Edit file dan folder Permissions, Kepemilikan dan Domain
SUBST Associate path dengan huruf drive
systeminfo konfigurasi sistem Daftar
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.
/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.
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
Save the file as C:\Users.txt and execute the command
AddUsers MyDomain /c c:\Users.txt /p:e
ATTRIB.exe
Syntax
ATTRIB [ + attribute | - attribute ] [pathname] [/S [/D]]
Key
+ : Turn an attribute ON
- : Clear an attribute OFF
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.
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.
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
"The moral sense of conscience is by far the most important.. it is the most noble of all the attributes of man"
- Charles Darwin
BOOTCFG.exe
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
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
CHKDSK.EXE
Syntax
CHKDSK [drive:][[path]filename] [/F] [/V] [/R] [/L[:size]]
Key
[drive:] The drive to check.
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.
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.
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
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
under Windows 2003 is around 30% faster than previous versions.
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.
"I either want less corruption, or more chance to participate in it" - Ashleigh Brilliant
CHKNTFS.exe
Syntax
CHKNTFS drive: [...]
CHKNTFS /C drive: [...]
CHKNTFS /X drive: [...]
CHKNTFS /t[:Time]
CHKNTFS /D
Key
drive : Specifies a drive letter.
CMD.exe
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 NT command, program or batch script to be run. This can even be several commands
separated with '&&' (the whole should also be surrounded by "quotes")
more below
Win2K / XP switches
The CMD switches below were first introduced with Windows 2000
At the command prompt Ctrl-D gives folder name completion and Ctrl-F gives file and folder name
completion.
These ctrl keys build up a list of paths that match and 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.
/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.
/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:
Command.com vs cmd.exe
All the commands on these pages assume you are running the 32 bit command line (cmd.exe)
CMD.exe is the NT/XP equivalent of Command.com in previous operating systems. The older 16 bit
command processor command.com is supplied to provide backward compatibility for 16 bit DOS
applications. e.g. command.com will fail to set %errorlevel% after certain commands.
To ensure that a batch file will not run if accidentally copied to a Windows 95/98 machine you should use
the extension .CMD rather than .BAT
The COMSPEC environment variable will show if you are running CMD.EXE or command.com
Subject to licensing issues, it is possible to run the Windows 2000 or Win XP version of CMD.EXE under NT.
This is not true of all commands, e.g. any command that involves NTFS disk access (such as cacls) should not
be moved between OS versions.
You can open a new CMD prompt by choosing START, RUN, cmd, OK
Registry Keys:
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)
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.
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
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
Under Windows NT, the command line is limited to 256 characters.
Under Windows 2000, the command line is limited to 2046 characters.
Under Windows XP, the command line is limited to 8190 characters.
For all OS's NTFS and FAT allows pathnames of up to 260 characters.
The above limits are often encountered when using long share names or drag and dropping files onto a batch
script.
Full Screen
The key combination ALT and 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
COPY
Syntax
COPY source 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.
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
function copycon {
[system.console]::in.readtoend()
}
Examples:
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"
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
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
Examples:
To delete HelloWorld.TXT
DEL HelloWorld.TXT
Folders
If a folder name is given instead of a file, all files in the folder will be deleted, but the folder itself will not be
removed.
Temporary Files
You should clear out TEMP files on a regular basis - this is best done at startup when no applications are
running. To delete all files in all subfolders of C:\temp\ but leave the folder structure intact:
DEL /F /S /Q %TEMP%
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:
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.
DIR
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:
[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:
[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 only)
/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
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 /
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)
Since TYPE won't lock the file_being_downloaded in any way, this doesn't pose a threat to the download
itself.
DISKCOPY.com
Syntax
DISKCOPY flopppy_drive1: floppy_drive2: [/V]
Key
/V Verify that the information was copied correctly.
"The great secret that all old people share is that you really haven't changed in seventy or eighty years. Your
body changes, but you don't change at all. And that, of course, causes great confusion." - Doris Lessing
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.
EXPAND
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
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.
Powershell also has an Alias FC for the Format-Custom command, therefore to run the 'old' FC under
powershell you need to explicitly run C:\windows\system32\fc.exe
FORMAT.com
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.
/F:size size is the size of the floppy disk (720, 1.2, 1.44, 2.88, or 20.8).
Example
@echo off
Echo Warning this will reformat the entire D: disk!
PAUSE
format D: /FS:NTFS /x
"The disks had a recording density of 1,100 bits per inch, and could move data out of the drive at 77 kilobytes
per second" - Early hard drive specs.
FTP
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
close End the FTP session and return to the cmd prompt.
debug Toggle debugging. When debug is on, FTP will display every command.
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.
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.
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)
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.
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.
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.
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.
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.
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
::PutFiles.ftp
[User_id]
[ftp_password]
binary
mput *.html
cd images
mput *.gif
quit
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 e.g. WinSCP
"Only wimps use tape backup: _real_ men just upload their important stuff on ftp, and let the rest of the world
mirror it" - Linus Torvalds
GOTO
Syntax
GOTO label
Key
label : a predefined label in the batch program. Each label must be on a line by itself, beginning
with a colon.
To exit a batch script file or exit a subroutine specify GOTO:eof this will transfer control to the end of the
current batch file, or the end of the current subroutine.
Examples:
:MySubroutine
Echo the input was 12
goto:eof
:s_routine_0
Echo You typed Y for yes
goto:eof
:s_routine_1
Echo You typed N for no
goto:eof
IF
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.
IF EXIST filename will return true if the file exists (this is not case sensitive).
IF ERRORLEVEL statements should be read as IF Errorlevel >= number i.e.
IF ERRORLEVEL 0 will return TRUE when the errorlevel is 64
IF ERRORLEVEL 1 will return TRUE when the errorlevel is 2
IF ERRORLEVEL 1 will return FALSE when the errorlevel is 0
Examples:
Does %1 exist?
To test for the existence of a command line parameter - use empty brackets like this
In the case of a variable that may be NULL - a null variable will remove the variable definition altogether, so
testing for NULLs becomes easy:
IF 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)
Any test made using the compare-op syntax will always be a "string" comparison,
so when comparing numbers note that "026" > "26"
Wildcards
Simple wildcards are not supported by IF, so ==SS6* will not match SS64
Pipes
ERRORLEVEL
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.
You see things; and you say 'Why?' But I dream things that never were; and I say 'why not?' - George Bernard
Shaw
IPCONFIG
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.
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
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 /?
If you're going to tell people the truth, you'd better make them laugh. Otherwise they'll kill you. - George
Bernard Shaw
LABEL
Syntax
LABEL [drive:][label]
The disk label is never referred to by other batch commands, it's just for human recognition.
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.
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 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 11 – CachedInteractive - mobile users not connected to the network connecting with cached
credentials.
"The man who is tired of London is tired of looking for a parking space" - Paul Theroux
MEM
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
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
will create
C:\temp\Alpha\
C:\temp\Beta\
C:\temp\Gamma\
MD \utils\downloads\Editor
md \utils
cd \utils
md downloads
cd downloads
md 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
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:
MOVE
Syntax
MOVE [options] [Source] [Target]
Key
source : The path and filename of the file(s) to move.
target : The path and filename to move file(s) to.
options: (Windows 2000 only)
/Y Suppress confirmation prompt.
/-Y Enable confirmation prompt.
Under Windows 2000 the default action is to prompt on overwrites unless the 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).
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:
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.
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
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
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.
MSTSC
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:
On the Windows XP CD, under \SUPPORT\TOOLS you'll find MSRDPCLI.exe. This is the setup for use with
9.x/2000 machines.
"Ignorance is preferable to error; and he is less remote from the truth who believes nothing, than he who
believes what is wrong" - Thomas Jefferson
MSIEXEC
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
"People don't resist change. They resist being changed!" - Peter Senge.
NETSTAT.exe
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; maybe 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.
PATH
Syntax
PATH pathname [;pathname] [;pathname] [;pathname]...
PATH
PATH ;
Key
pathname : drive letter and/or folder; : the command 'PATH ;' will clear the path
The %PATH% environment variable contains a list of folders. When a command is issued at the CMD
prompt, the operating system will first look for an executable file in the current folder, if not found it will
scan %PATH% to find it.
Use the PATH command to display or change the list of folders stored in the %PATH% environment variable.
To view each item on a single line use this:
Or in a batch file:
Note you do not need to surround each part of the path with double quotes, PATH will always treat spaces as
part of the filename.
Permanent Changes
Changes made using the PATH command are NOT permanent, they apply to the current CMD prompt only
and remain only until the CMD window is closed.
The %PATH% variable is set as both a system and user variable, the 2 values are combined to give the PATH
for the currently logged in user. This is explained in full by MS Product Support Article Q100843
Be wary of using commands like SETX to modify the PATH - the User path can be edited, but the System path
remains read-only for most users. If you try to delete an old value and add a new one it is very common for
the 'delete' to fail and the 'add' to succeed, resulting in duplicate values being added to the path.
If you are trying to modify the path to add settings for a single application, a reasonably safe method is to use
a second variable: e.g.
You can now easily change that one variable %MYAPP% at any time in the future and the PATH will reflect
the new value.
Changing a variable in the Control Panel will not affect any CMD prompt that is already open, only
new CMD prompts will get the new setting.
To change a system variable you must have administrator rights
If your system has an AUTOEXEC.BAT file then any PATH setting in AUTOEXEC.BAT will also be
appended to the %PATH% environment variable. This is to provide compatibility with old
installation routines which need to set the PATH. All other commands in AUTOEXEC.BAT are
ignored.
Terminology
"If you do not love your job, change it. Instead of pushing paper, push ideas. Instead of sitting down, stand up
and be heard. Instead of complaining, contribute. Don't get stuck in a job description" - Microsoft job advert
PING
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.
-l size Send buffer size.
-f Set Don't Fragment flag in packet.
-r count Record route for count hops.
-s count Timestamp for count hops.
-j host_list Loose source route along host_list.
-k host_list Strict source route along host_list.
destination_host The name of the remote host
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.
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.
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
A time of 10 milliseconds is roughly equal to a distance of 930 Miles, travelling a straight line route at the
speed of light.
"And now I see with eye serene The very pulse of the machine." - William Wordsworth, (She Was a Phantom of
Delight)
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%:.
You can also create a shortcut to the command prompt like this:
CMD /K PROMPT $M$_$P$G
If Command Extensions are disabled the commands $M and $+ are not supported.
Syntax
pskill [- ] [-t] [\\computer [-u user] [-p passwd]] <process name | process id>
Options:
Examples:
Kill all instances of notepad.exe running on \\workstation64:
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.
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:
Syntax
psshutdown [[\\computer[,computer[,..] | @file [-u user [-p passwd]]]
-s|-r|-h|-d|-k|-a|-l|-o
[-f] [-c] [-t nn|h:m] [-n s] [-v nn]
[-e [u|p]:xx:yy] [-m "message"]
Options:
computer The computer on which the user account resides. Default=local system
a wildcard (\\*), will affect all computers in the current domain.
-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 user name for login to remote computer(optional).
@file Execute the command on each of the computers listed in the file.
-a Abort a shutdown (only possible while a countdown is in progress)
-c Allow the shutdown to be aborted by the interactive user
-d Suspend the computer
-e [u|p]:xx:yy
Shutdown reason code, 'u' = user, 'p'= planned shutdown.
xx is the major reason code (must be less than 256)
yy is the minor reason code (must be less than 65536)
-f Force all running applications to exit during the shutdown
instead of giving them a chance to gracefully save their data.
-h Hibernate the computer
-k Poweroff the computer (reboot if poweroff is not supported)
-l Lock the computer
-m "message" Specify a message to logged-on users when a shutdown countdown commences
-n Timeout in seconds connecting to remote computers
-o Logoff the console user
-r Reboot after shutdown
-s Shutdown without poweroff
-t Countdown in seconds until the shutdown (default: 20 seconds) or the time of shutdown (in 24
hour notation)
-v Display message for the specified number of seconds before the shutdown.
default= display a shutdown notification dialog, specifying a value of 0 results in no dialog.
- Help, display the supported options.
This tool allows administrators to create a batch file that will run against multiple computers to perform a
mass change of the administrator password.
Examples:
PUSHD
Change the current directory/folder and store the previous folder/path for use by the POPD command.
Syntax
PUSHD pathname
Key
pathname - the folder to make 'current' (UNC names accepted)
Example
@Echo Off
Setlocal
Set _folder=%1
Pushd %_folder%
:: Now verify we really moved to the new folder
If /i not "%cd%"=="%_folder% (Echo folder not found &goto :eof)
Echo We are at %cd%
Popd
Echo We are back at %cd%
Networks
When a UNC path is specified, PUSHD will create a temporary drive map and will then use that new drive.
Temporary drive letters are allocated in reverse alphabetical order
so if Z: is free it will be used.
If Command Extensions are disabled the PUSHD command will not accept a network (UNC) path.
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
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
More examples are available via: REG QUERY /? REG ADD /? etc
"The way to a mans heart is through his stomach" - Fanny Fern (writer)
REGEDIT
Syntax
Export the Registry (all HKLM plus current user)
REGEDIT /E pathname
Export part of the Registry
REGEDIT /E pathname "RegPath"
Import a reg script
REGEDIT pathname
Silent import
REGEDIT /S pathname
Start the regedit GUI
REGEDIT
Open multiple copies of GUI (XP and 2003 only)
REGEDIT -m
Key
/E : Export
/S : Silent Import
When double clicking this .reg file the key and value will be added. Alternatively run REGEDIT MYKEY.REG
from the command line.
Create a reg file like this, notice the hyphen inside the first bracket
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.
Again double clicking this .reg file will delete the values specified, or you can use REGEDIT /s
MyDeleteScript.REG
Windiff is your friend, this simple GUI utility from the resource kit will list all the differences.
Comments
Under Windows NT 4 all registry scripts start with: REGEDIT4 (This version string will also work in XP and
later versions of Windows.)
"I never make stupid mistakes. Only very, very clever ones" - John Peel
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
"If you're rich you can buy books. If you're poor, you need a library" - John Kenneth Galbraith
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.
e.g.
REN *.txt *.xyz
REN c:\MyFile.txt *.xyz
REN c:\MyFile.txt ????.xyz
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
RD does not support wildcards but you can remove several folders in one command by listing the pathname
to each. e.g.
"Dying is the most embarrassing thing that can happen to you, because someones got to take care of all your
details". - Andy Warhol
ROUTE.exe
Manipulate network routing tables. Route packets of network traffic from one subnet to another by
modifying the route table.
Syntax
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.
interface The interface number (1,2,...) for the specified route. the best interface available.
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*
Syntax
Display all shares
RMTSHARE \\server
Display details of a specific share
RMTSHARE \\server\sharename
Share a Folder
RMTSHARE \\server\sharename=drive:path [options]
Share a Printer
RMTSHARE \\server\sharename=printername /PRINTER [options]
Edit an existing SHARE
RMTSHARE \\server\sharename [options]
Delete a SHARE
RMTSHARE \\server\sharename /DELETE
Options
/USERS:number
/UNLIMITED
/REMARK:"text"
/GRANT user:perm
/REMOVE user
Notes: Either specify /Users to restrict the number of connections that can be made OR specify /UNLIMITED
You can include several /GRANTs in a single command line. Enclose paths that include spaces like
this
\\server\"long share name"="c:\long file name"
"How to be green? consume less, share more, enjoy life" - Penny Kemp
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.
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
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
@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
Set /P _MyVar=<MyFilename.txt
CALL SET
SET can be CALLed allowing a variable substring to be evaluated:
SET start=10
SET length=9
SET string=The quick brown fox jumps over the lazy dog
CALL SET substring=%%string:~%start%,%length%%%
ECHO (%substring%)
Type SET with just the variable name and an equals sign:
SET _department=
A variable can contain spaces and also the variable name itself may contain spaces, therefore the following
assignment:
SET my var=MyText
will create a variable called "my var"
Similarly
SET _var =MyText
will create a variable called "_var " - note trailing space
To avoid problems with extra spaces appearing in your output, issue SET statements in parentheses, like this
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
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
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
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)
Autoexec.bat
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
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
Deleting a variable in this way does not take effect until next logon due to caching of registry data. The type
is REG_EXPAND_SZ.
Examples:
Set the variable "_myTimeZone" in both the immediate user session and the permanent environment:
SET _myTimeZone=GMT
SetX _myTimeZone GMT
Sets the value of _mypath to ALWAYS be equal to the value of the %PATH% environment variable even in
the event that the PATH variable changes:
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.
Although missing from recent Resource Kits, this VBS script does still work under 2K/XP. 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>]
Options:
/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:
Syntax
SHUTDOWN [logoff_option] [/m \\Computer] [options]
logoff_option:
/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:
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 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)
Example:
To create a desktop shortcut that will immediately shutdown your system, set the shortcut Target Properties
to:
C:\Windows\System32\shutdown.exe -s
When using this command to reboot a server, the shutdown process will normally allow about 30 seconds to
ensure each running service has time to stop. The shutdown can be made faster if all the services are first
halted using NET STOP
e.g.
net stop "Microsoft Exchange Internet Mail Service"
net stop "Microsoft FTP Service"
net stop "Some other Service"
SHUTDOWN /t:25 /r
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 fixed delay can also be produced by the PING command with a loopback address:
See Clay Calvert's newsgroup posting for a full explanation of this technique.
Syntax
slmgr [MachineName [Username Password]] [Option]
Key
-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
-xpr Show the expiry date of current license (if not permanently activated)
-upk Uninstall current installed product key and return license status back to trial state.
-ato Activate Windows license and product key against Microsoft's server.
-atp Confirmation_ID Activate Windows with user-provided Confirmation ID
-skms activationservername
or
-skms port
or
-skms activationservername:port Set the KMS server and the port used for KMS activation
(where supported by your Windows edition)
-rearm Reset the evaluation period/licensing status and activation state of the machine
-ckms Clear the name of KMS server used to default and port to default.
-cpky Clear product key from the registry (prevents disclosure attacks)
-ilc License_file Install license
-rilc Re-install system license files
machinename The machine to administer, by default the current local machine.
username An administrator equivalent user account for the computer.
password The password for the user account.
SUBST
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.
"A man should never be ashamed to own he has been in the wrong, which is saying in other words, that he is
wiser today than he was yesterday" - Alexander Pope (thoughts on various subjects)
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:
Examples:
tasklist /svc
tasklist /v /fi "STATUS eq running"
tasklist /v /fi "username eq ORACLE_SERVICE_ACCOUNT"
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:
If Command Extensions are disabled TIME will not support the /T switch
“Time is like money, the less we have of it to spare, the further we make it go” - Josh Billings
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.
Timeout.exe seems to consume less processor time time than Sleep.exe
"It is awful work this love and prevents all a mans projects of good or glory" - Lord Byron
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)
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
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 a CTRL - Z to indicate end of file.
When using redirection to SORT a file the TYPE command is used implicitly
For example:
SORT < MyFile.txt
If you TYPE a Unicode text file, the output will be ANSI (note any extended characters will be lost)
eg:
TYPE UnicodeFile.txt > ANSIFile.txt
@echo off
ren *.txt *.txx
for %%G in (*.txx) do (TYPE %%G >%%~nG.txt)
echo del *.txx
VOL
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 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.
VER
Syntax
VER
@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)
:sub5
::Winxp 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
This Batch script will give the Service Pack level. Works for NT, Win2K or WinXP
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
Examples
Find all files named 'Zappa' on the remote computer 'Server1' searching its subdirectories, and reporting the
executable type for executable files
"Who never walks, save where he sees men's tracks, makes no discoveries" - Josiah Gilbert Holland
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:>whoami
ss64\JDoe
"We can now manipulate images to such an extrodinary extent that there's no lie you cannot tell" - Sir David
Attenborough
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.
Registry files (exported with regedit) can also be compared. Also see the help file Windiff.hlp.
Downloads
"Shall I compare thee to a summer's day? Thou art more lovely and more temperate.
Rough winds do shake the darling buds of May, And summer's lease hath all too short a date" - Shakespeare
WINMSD.exe
Syntax
WINMSD [\\computername] options
Options:
/a All details
/s Summary details only
/f Send output to a file <computername.txt> in the current directory
/p Send output to a printer
WINMSD with no switches will open the GUI with details of the computer you are logged into.
It is advisable to have the SERVER service running, if not - winmsd will show a warning dialogue.
Spooling output to file - if you have the resource kit WINMSDP allows more control over this.
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
WMIC.exe
Syntax
Retrieve information about <Alias>:
WMIC [global_switches] [/locale:ms_409] <alias> [options] [format]
Interactive mode:
WMIC
Aliases:
ALIAS - Access local system aliases [CALL]
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]
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: 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 /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, for older machines download & install: WMI core
for Win 9x / NT 4
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.
"Life is like a game of cards. The hand you are dealt is determinism; the way you play it is free will" - Jawaharial
Nehru
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:
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.
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 suppport unc paths and is very
slow to update multiple ACLs.
Examples:
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.
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).
/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
Destination Options
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
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 WinXP version of XCOPY will accept wildcards for the source e.g. *.txt It is also more forgiving with
trailing backslashes
REM
@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.
The bottom line on this is that you must test your comments to be sure they will be ignored as you expect.
Registry Comments
FTP Comments
There is no valid comment character for FTP but you can cheat by escaping to the shell and running REM
e.g.
C:\WORK>type ftpscript
!REM This is a remark
bye
C:\WORK>ftp -s:ftpscript
ftp> !REM This is a remark
ftp> bye
C:\WORK>
The603h – 17/01/2010