windows command prompt a to z
Post on 20-Jun-2015
1.425 Views
Preview:
TRANSCRIPT
Windows Command Prompt www.nubielab.com Page 1
Windows Command Prompt www.nubielab.com Page 2
ADDUSERS.exe Automate the creation of a large number of users Syntax
Create Users:
AddUsers /c filename [/s:x] [/?] Domain
Password_options
Dump to file:
AddUsers /d{:u} filename [/s:x] [/?] Domain
Password_options
Erase Users:
AddUsers /e filename [/s:x] [/?] Domain
Password_options
key
Filename - The comma-delimited file that AddUsers uses for
data.
/s:x - Change the delimiter character used in filename
to x.
e.g. /s:~ would make the
delimiter "~"
Domain - Query the Primary Domain Controller (PDC) of
domain.
You can also use \\Servername to specify the
machine where user accounts are created or read.
AddUsers will use the local computer by default
(if you do not specify Domain)
/c - Create user accounts, local groups, and global
groups as specified by filename.
/d{:u} - Dump user accounts, local groups, and global
groups to filename.
The (:u) is an optional switch that causes current accounts to be written to the specified file in
Unicode text format. Choosing to dump current user accounts does not save the account's
passwords or any security information for the accounts.
Note: Password information is not saved in a user account dump and if you use the same file to
create accounts, all passwords of newly created accounts will be empty. To back up security
information for accounts, use a Tape Backup. /e - Erase the user accounts specified in the file
name.
CAUTION: Be careful when erasing user accounts,
as it is not possible to recreate
an account with the same SID.
This option will not erase built-in accounts.
Password_options
/p: - Set account creation options, used along with
any combination of the following:
* l - Users do not have to change passwords at next
logon.
* c - Users cannot change passwords.
* e - Passwords never expire. (implies l option)
* d - Accounts disabled.
By default, all created users are required to
change their password at logon.
Example
Create a comma-delimited text file, which contains the new users to be created. Following the
Syntax as follows:
[Users]
User Name,Full name, Password, Description, HomeDrive, Homepath, Profile, Script
e.g.
[User]
jimmye,James Edward Phillip II,,,,,,
alexd,Alex Denuur,,,E:\,E:\users\alexd,,
ronj,Ron Jarook,ChangeThis,,E:\,E:\users\ronj,,
sarahs,Sarah Smith,,,,,,
u0123,Mike Olarte,,,,,,
Save the file as C:\Users.txt and execute the command
AddUsers MyDomain /c c:\Users.txt /p:e
ARP.exe ARP - Address Resolution Protocol
Display and modify the IP-to-Physical address translation tables used by address resolution
protocol. Syntax
View the contents of the local ARP cache table
ARP -a [ip_addr] [-N if_addr]
Add a static Arp entry for frequent accessed hosts
ARP -s ip_addr eth_addr [if_addr]
Delete an entry
ARP -d ip_addr [if_addr]
Windows Command Prompt www.nubielab.com Page 3
Key
-a Display current ARP entries.
May include more than one network interface.
If ip_addr is specified, the IP and Physical
addresses for only the specified computer are
displayed.
-g Same as -a.
-N if_addr Display the ARP entries for the network
interface specified
by if_addr.
-d ip_addr Delete the host specified by ip_addr.
-d * will delete all hosts.
-s Add the host and associates the Internet address
ip_addr
with the Physical address eth_addr. The
Physical address is
given as 6 hexadecimal bytes separated by
hyphens. The entry
is permanent.
eth_addr Specifies a physical address.
if_addr If present, this specifies the Internet address
of the
interface whose address translation table should
be modified.
If not present, the first applicable interface
will be used.
If two hosts on the same sub-net cannot ping each other successfully, try running ARP -a to list
the addresses on each computer to see if they have the correct MAC addresses.
A host's MAC address can be checked using IPCONFIG. If another host with a duplicate IP
address exists on the network, the ARP cache may have had the MAC address for the other
computer placed in it. ARP -d is used to delete an entry that may be incorrect.
Examples Display the ARP cache tables for all interfaces:
C:\> arp -a
Display the ARP cache table for the interface on IP address 10.1.4.99:
C:\> arp -a -N 10.1.4.99
Add a static ARP cache entry on IP addr 10.1.4.77 to the physical address 00-AA-21-4A-2F-9A:
C:\> arp -s 10.1.4.77 00-AA-21-4A-2F-9A
ASSOC
Display or change the association between a file extension and a fileType
Syntax
ASSOC .ext = [fileType]
ASSOC
ASSOC .ext
ASSOC .ext =
Key
.ext : The file extension
fileType : The type of file
A file extension is the last few characters in a FileName after the period.
So a file called JANUARY.HTML has the file extension .HTML
The File extension is used by Windows NT to determine the type of information stored in the file
and therefore which application(s) will be able to display the information in the file. File
extensions are not case sensitive and are not limited to 3 characters.
More than one file extension may be associated with the same File Type.
e.g. both the extension .JPG and the extension .JPEG may be associated with the File Type
"jpegfile"
At any one time a given file extension may only be associated with one File Type.
e.g. If you change the extension .JPG so it is associated with the File Type "txtfile" then it's
normal association with "jpegfile" will disappear. Removing the association to "txtfile" does not
restore the association to "jpegfile"
File Types can be displayed in the Windows Explorer GUI: [View, Options, File Types]
however the spelling is usually different to that expected by the ASSOC command e.g. the File
Type "txtfile" is displayed in the GUI as "Text Document"and "jpegfile" is displayed as
"image/jpeg"
The command ASSOC followed by just a file extension will display the current File Type for
that extension.
ASSOC without any parameters will display all the current file associations.
ASSOC with ".ext=" will delete the association for that file extension.
Did you leave the Always Use This Program To Open This File option turned on?
To change it back so it prompts you to specify a program each time, just delete the association
for that file type
ASSOC .ext=
[where .ext is the file extension].
Now when you double-click on a file of that type, the system will ask you what program you
want to use.
Using the ASSOC command will edit values stored in the registry at HKey_Classes_Root\.<file
Windows Command Prompt www.nubielab.com Page 4
extension>
Therefore it's possible to use registry permissions to protect a file extension and prevent any file
association changes.
Examples:
Viewing file associations:
ASSOC .txt
ASSOC .doc
ASSOC >backup.txt
Editing file associations:
ASSOC .txt=txtfile
ASSOC .DIC=txtfile
ASSOC .html=Htmlfile
Deleting a file association:
ASSOC .html=
Repair .REG and .EXE file associations:
ASSOC .EXE=exefile
ASSOC .REG=regfile
Digging through CLASSES_ROOT entries often reveals more than one shell for the same
application, for example the Apple Quick Time player has two entries, one to "open" (which
gives an annoying nag screen) and one to just "play" the QT file:
[HKEY_CLASSES_ROOT\MOVFile\shell\open] and [play]
In cases like this you can change the default action e.g.
[HKEY_CLASSES_ROOT\MOVFile\shell]
@="play"
ASSOCIATE.exe (Resource Kit) One step file association.
This utility does the job of both ASSOC and FTYPE, in one step. ASSOCIATE assigns an
extension directly with an executable application. This is done by automatically adding a new
FileType to the system registry. Syntax
ASSOCIATE .ext filename [/q /d /f]
Key
.ext : Extension to be associated.
filename : Executable program to associate .ext with.
/q : Quiet - Suppress interactive prompts.
/f : Force - Force overwrite or delete without
questions.
/d : Delete - Delete the association.
A file extension is the last few characters in a FileName after the period.
So a file called JANUARY.HTML has the file extension .HTML
The File extension is used by Windows NT to determine the type of information stored in the file
and therefore which application(s) will be able to display the information in the file. File
extensions are not case sensitive and are not limited to 3 characters.
Example: adding a File Association
To add the File Type "SQLfile"=Notepad.exe and also set the File Association of
.SQL="SQLfile" run this command:
ASSOCIATE .SQL Notepad.exe
Example: Removing a File Association
ASSOCIATE .SQL /d
Note that /d will delete the File Association but will NOT delete the File Type.
File types created by Associate.exe are always given a name in the form xxxfile, where xxx is
the file extension.
ATTRIB.exe
Display or change file attributes. Find Filenames. Syntax
ATTRIB [ + attribute | - attribute ] [pathname] [/S [/D]]
Key
+ : Turn an attribute ON
- : Clear an attribute OFF
pathname : Drive and/or filename e.g. C:\*.txt
/S : Search the pathname including all subfolders.
/D : Process folders as well
attributes:
R Read-only (1)
H Hidden (2)
A Archive (32)
S System (4)
Windows Command Prompt www.nubielab.com Page 5
extended attributes:
E Encrypted
C Compressed (128:read-only)
I Not content-indexed
L Symbolic link/Junction (64:read-only)
N Normal (0: cannot be used for file selection)
O Offline
P Sparse file
T Temporary
The numeric values may be used when changing attributes with VBS/WSH
If no attribute is specified attrib will return the current attribute settings. Used with just the /S
option ATTRIB will quickly search for a particular filename.
Hidden and System attributes take priority.
If a file has both the Hidden and System attributes set, you can clear both attributes only with a
single ATTRIB command.
For example, to clear the Hidden and System attributes for the RECORD.TXT file, you would
type:
ATTRIB -S -H RECORD.TXT
File Attributes
You can use wildcards (? and *) with the filename parameter to display or change the attributes
for a group of files.
Remember that, if a file has the System or Hidden attribute set, you must clear that attribute
before you can change any other attributes.
Directory Attributes
You can display or change the attributes for a directory/folder. To use ATTRIB with a directory,
you must explicitly specify the directory name; you cannot use wildcards to work with
directories.
For example, to hide the directory C:\SECRET, you would type the following:
ATTRIB +H C:\SECRET
The following command would affect only files, not directories: ATTRIB +H C:*.*
The Read-only attribute for a folder is generally ignored by applications, however the Read-only
and System attributes are used by Windows Explorer to determine whether the folder is a special
folder, such as My Documents, Favorites, Fonts, etc.
Setting the Read-Only attribute on a folder can affect performance, particularly on shared drives
because Windows Explorer will be forced to request the Desktop.ini of every sub-folder to see if
any special folder settings need to be set.
Viewing archive attributes
The Archive attribute (A) is used to mark files that have changed since they were previously
backed up. The (A) flag is automatically updated by Windows as the file is saved.
If the (A) flag is present - the file is new or has been changed since the last backup.
The MSBACKUP, RESTORE, and XCOPY commands use these Archive attributes, as do many
(but not all) 3rd party backup solutions.
Constants - the following attribute values are returned by the GetFileAttributes function:
FILE_ATTRIBUTE_READONLY = 1
FILE_ATTRIBUTE_HIDDEN = 2
FILE_ATTRIBUTE_SYSTEM = 4
FILE_ATTRIBUTE_DIRECTORY = 16
FILE_ATTRIBUTE_ARCHIVE = 32
FILE_ATTRIBUTE_ENCRYPTED = 64
FILE_ATTRIBUTE_NORMAL = 128
FILE_ATTRIBUTE_TEMPORARY = 256
FILE_ATTRIBUTE_SPARSE_FILE = 512
FILE_ATTRIBUTE_REPARSE_POINT = 1024
FILE_ATTRIBUTE_COMPRESSED = 2048
FILE_ATTRIBUTE_OFFLINE = 4096
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192
BCDBOOT.exe (Windows 7 /2008) Set up a system partition, repair the boot environment located on the system partition. Syntax
BCDBOOT source [/l locale] [/s volume-letter]
[/v] [/m [{OS Loader GUID}]]
Options
source The location of the Windows directory to use as the
source for
copying boot-environment files.
/l The locale. default = US English.
/s The volume letter of the system partition.
The default is the system partition identified by the
firmware.
Windows Command Prompt www.nubielab.com Page 6
/v Enable verbose mode
/m By default, merge only global objects.
If an OS Loader GUID is specified, merge the given
loader object within
the system template to produce a bootable entry.
BCDboot may also be run from Windows PE (Preinstallation Environment)
Examples Initialize the system partition using files from the operating system image installed on the C:
volume:
C:\> bcdboot C:\Windows
Set the default BCD locale to Japanese, and copy BCD (Boot Configuration Data) files to drive
S:
C:\> bcdboot C:\Windows /l ja-jp /s S:
Merge the OS loader in the current BCD store identified with the given GUID in the new BCD
store:
C:\> bcdboot c:\windows /m {d58d10c6-df53-11dc-878f-00064f4f4e08}
BOOTCFG.exe Edit the Windows boot settings stored in Boot.ini Syntax
BOOTCFG /addsw Add OS load options for an OS entry in
boot.ini
BOOTCFG /copy Duplicate the entries for an OS
instance.
BOOTCFG /dbg1394 Configure 1394 port debugging
BOOTCFG /debug Edit the debug settings for an OS.
BOOTCFG /default Specify the default OS
BOOTCFG /delete Delete an OS entry [operating systems]
section of Boot.ini
BOOTCFG /ems Redirect the EMS console to a remote
computer (server only).
(Emergency Management Services)
BOOTCFG /list List entries in boot.ini
BOOTCFG /query Display section entries from Boot.ini
BOOTCFG /raw Add OS load options, specified as a
string
BOOTCFG /rebuild Totally rebuild boot.ini (use when
Windows won't start)
BOOTCFG /rmsw Remove OS load options for an OS
BOOTCFG /timeout Change the OS time-out value.
Detailed options for all the above are available from BOOTCFG /? Items in bold are only
available from the recovery console
Default identification strings:
OS Load Options = /Fastdetect
Load Identifier = Microsoft Windows XP Professional
If you intend to rebuild the boot.ini file, delete it first - boot into the recovery console then: ATTRIB -H -R -S C:\Boot.ini
DEL C:\Boot.ini
Bootcfg /Rebuild
Fixboot
CACLS.exe Display or modify Access Control Lists (ACLs) for files and folders.
Access Control Lists apply only to files stored on an NTFS formatted drive, each ACL
determines which users (or groups of users) can read or edit the file. When a new file is created it
normally inherits ACL's from the folder where it was created. Syntax
CACLS pathname [options]
Options:
/T Search the pathname including all subfolders.
/E Edit ACL (leave existing rights unchanged)
/C Continue on access denied errors.
/G user:permission
Grant access rights, permision can be:
R Read
W Write
C Change (read/write)
F Full control
/R user
Windows Command Prompt www.nubielab.com Page 7
Revoke specified user's access rights (only valid with
/E).
/P user:permission
Replace access rights, permission can be:
N None
R Read
W Write
C Change (read/write)
F Full control
/D user
Deny access to user.
In all the options above "user" can be a UserName or a Workgroup (either local or global)
You can specify more than one user:permission in a single command. Wildcards can be used to
specify multiple files.
If a UserName or WGname includes spaces then it must be surrounded with quotes e.g.
"Authenticated Users"
If no options are specified CACLS will display the ACLs for the file(s)
Setting Deny permission (/D) will deny access to a user even if they also belong to a group that
grants access.
Limitations Cacls cannot display or modify the ACL state of files locked in exclusive use.
Cacls cannot set the following permissions: change permissions, take ownership, execute, delete
use XCACLS to set any of these.
Using CACLS
The CACLS command does not provide a /Y switch to automatically answer 'Y' to the Y/N prompt. However, you can pipe the 'Y' character into the CACLS command using ECHO, use the following syntax: ECHO Y| CACLS /g <username>:<permission>
To edit a file you must have the "Change" ACL (or be the file's owner)
To use the CACLS command and change an ACL requires "FULL Control"
File "Ownership" will always override all ACL's - you always have Full Control over files that you create.
If CACLS is used without the /E switch all existing rights on [pathname] will be replaced, any attempt to use the /E switch to change a [user:permission] that already exists will raise an error. To be sure the CALCS command will work without errors use
/E /R to remove ACL rights for the user concerned, then use /E to add the desired rights.
The /T option will only traverse subfolders below the current directory. If no options are specified CACLS will display the current ACLs
e.g. To display the current folder
CACLS .
Display permissions for one file
CACLS MyFile.txt
Display permissions for multiple files
CACLS *.txt
Inherited folder permissions are displayed as: OI - Object inherit - This folder and files. (no inheritance
to subfolders)
CI - Container inherit - This folder and subfolders.
IO - Inherit only - The ACE does not apply to the current
file/directory
These can be combined as folllows:
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
(OI) (IO) Files only.
So BUILTIN\Administrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F'
(Fullcontrol)
similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)
To actually change the inheritance of a folder/directory use iCACLS /grant or iCACLs /deny
When cacls is applied to the current folder only there is no inheritance and so no output.
Errors when changing permissions If a user or group has a permission on a file or folder and you grant a second permission to the
same user/group on the same folder, NTFS will sometimes produce the error message "The
parameter is incorrect" To fix this (or prevent it happening) revoke the permission first (/e /r) and
then reapply (/e /g)
Examples:
Add Read-Only permission to a single file
CACLS myfile.txt /E /G "Power Users":R
Add Full Control permission to a second group of users
CACLS myfile.txt /E /G "FinanceUsers":F
Now revoke the Read permissions from the first group
CACLS myfile.txt /E /R "Power Users"
Now give the first group Full-control:
CACLS myfile.txt /E /G "Power Users":F
Windows Command Prompt www.nubielab.com Page 8
Give the Finance group Full Control of a folder and all sub folders
CACLS c:\docs\work /E /T /C /G "FinanceUsers":F
CALL Call one batch program from another. Syntax
CALL [drive:][path]filename [parameters]
CALL :label [parameters]
CALL internal_cmd
Key:
pathname The batch program to run
parameters Any command-line arguments
:label Jump to a label in the current batch script.
internal_cmd Any internal command, first expanding any
variables in the argument
CALL a second batch file
The CALL command will launch a new batch file context along with any specified arguments.
When the end of the second batch file is reached (or if EXIT is used), control will return to just
after the initial CALL statement.
CALL a subroutine (:label)
The CALL command will pass control to the statement after the label specified along with any
specified arguments .
To exit the subroutine specify GOTO:eof this will transfer control to the end of the current
subroutine.
Arguments can be passed either as a simple string or using a variable:
CALL MyScript.cmd "1234"
CALL OtherScript.cmd %_MyVariable%
Use a label to CALL a subroutine
A label is defined by a single colon followed by a name. This is the basis of a batch file function.
CALL :s_display_result 123
ECHO Done
GOTO :eof
:s_display_result
ECHO The result is %1
GOTO :eof
At the end of the subroutine, GOTO :eof will return to the position where you used CALL.
Example @ECHO OFF
SETLOCAL
CALL :s_staff SMITH 100
GOTO s_last_bit
:s_staff
ECHO Name is %1
ECHO Rate is %2
GOTO :eof
:s_last_bit
ECHO The end of the script
Advanced usage : CALLing internal commands
In addition to the above, CALL can also be used to run any internal command (SET, ECHO etc)
and also expand any environment variables passed on the same line.
For example @ECHO off
SETLOCAL
set server1=frodo3
set server2=gandalf4
set server3=ascom5
set server4=last1
::run the Loop for each of the servers
call :loop server1
call :loop server2
call :loop server3
call :loop server4
goto:eof
:loop
set _var=%1
:: Evaluate the server name
CALL SET _result=%%%_var%%%
echo The server name is %_result%
goto :eof
:s_next_bit
:: continue below
Windows Command Prompt www.nubielab.com Page 9
:: Note the line shown in bold has three '%' symbols
:: The CALL will expand this to: SET _result=%server1%
Each CALL does one substitution of the variables. (You can also do CALL CALL... for multiple
substitutions)
If you CALL an executable or resource kit utility make sure it's available on the machine where
the batch will be running, also check you have the latest versions of any resource kit utilities.
If Command Extensions are disabled, the CALL command will not accept batch labels.
CD Change Directory - Select a Folder (and drive) Syntax
CD [/D] [drive:][path]
CD [..]
Key
/D : change the current DRIVE in addition to changing folder.
Examples To change to the parent directory.
C:\Work> CD ..
To change to the grant-parent directory.
C:\Work\backup\January> CD ..\..
To change to the ROOT directory.
C:\Work\backup\January> CD \
To display the current directory in the specified drive.
C:\> CD D:
To display the current drive and directory.
C:\Work> CD
To display the current drive and directory.
C:\Work> ECHO "%CD%"
In a batch file to display the location of the batch script
file (%0)
C:\> ECHO "%~dp0"
Moving down the folder tree with a full path reference to the
ROOT folder...
C:\windows> CD \windows\java
C:\windows\java>
Moving down the folder tree with a reference RELATIVE to the
current folder...
C:\windows> CD java
C:\windows\java>
Moving up and down the folder tree in one command...
C:\windows\java> CD ..\system32
C:\windows\system32>
If Command Extensions are enabled the CD command is enhanced as follows:
1) The current directory string is converted to use the correct CASE.
So CD C:\wiNnt would actually set the current directory to C:\Winnt
2) CD does not treat spaces as delimiters, so it is possible to CD into a subfolder name that
contains a space without surrounding the name with quotes.
For example:
cd \My folder
is the same as:
cd "\My folder"
3) An asterisk can be used to complete a folder name
e.g. from C:\
C:> CD pro*
will move to
C:\Program Files
CHDIR is a synonym for CD
Tab Completion
This allows changing current folder by entering part of the path and pressing TAB C:> CD Prog [PRESS TAB]
Will go to C:\Program Files\
Tab Completion is disabled by default, it has been known to create difficulty when using a batch
script to process text files that contain TAB characters.
Tab Completion is turned on by setting the registry value shown below
REGEDIT4
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"CompletionChar"=dword:00000009
Changing the Current drive
Windows Command Prompt www.nubielab.com Page 10
simply enter the drive letter followed by a colon
C:> E:
E:>
To change drive and directory at the same time, use CD with the /D switch
C:> cd /D E:\utils
E:\utils\>
chkdsk.exe Check Disk - check and repair disk problems Syntax
CHKDSK [drive:][[path]filename] [/F] [/V] [/R] [/L[:size]]
Key
[drive:] The drive to check.
filename File(s) to check for fragmentation (FAT only).
/F Automatically Fix file system errors on the disk.
/X Fix file system errors on the disk, (Win2003 and
above)
dismounts the volume first, closing all open file
handles.
/R Scan for and attempt Recovery of bad sectors.
/V Display the full path and name of every file on
the disk.
/L:size NTFS only: change the log file size to the
specified number of kilobytes.
If size is not specified, displays the current log
size and the drive type
(FAT or NTFS).
/C Skip directory corruption checks.
/I Skip corruption checks that compare directory
entries to the
file record segment (FRS) in the volume's master
file table (MFT)
Example:
CHKDSK C: /F
Fixing Errors /F
If the drive is the boot partition, you will be prompted to run the check during the next boot
If you specify the /f switch, chkdsk will show an error if open files are found on the disk.
Chkdsk /f will lock the volume, making data unavailable until chkdsk is finished.
If you use chkdsk /f on a disk with a very large number of files (millions), chkdsk may take a
long time to complete.
When you delete a file or folder that has 'custom' permissions, the ACL is not deleted, it is
cached. Chkdsk /f will remove ACLs that are no longer used. This is often the cause of the rather
worrying message: "Windows found problems with the file system. Run chkdsk with the /F (fix)
option to correct these."
It is normal for chkdsk /F to remove unused index entries and unused security descriptors every
time you run it, these do not indicate a problem with the file system.
Scan only (without /f switch)
If a file needs to be fixed chkdsk will alert you with a message but will not fix the error(s).
chkdsk may report lost allocation units on the disk - it will produce this report even if the files
are in-use (open). If corruption is found, consider closing all files and repairing the disk with /F.
Running chkdsk on a data volume that is in use by another program or process may incorrectly
report errors when none are present. To avoid this, close all programs or processes that have
open handles to the volume.
On computers running Windows 2003 SP1, chkdsk automatically creates a shadow copy, so you
can check volumes that are 'in use' by another program or process. This enables an accurate
report against a live file server. On earlier versions of Windows, chkdsk would always lock the
volume, making data unavailable.
Run at Bootup Running at bootup is often the easiest way to close all open file handles.
Use the GUI, chkntfs or the FSUTIL dirty commands to set or query the volumes 'dirty' bit so
that Windows will run chkdsk when the computer is restarted.
Event Logs Chkdsk will log error messages in the Event Viewer - System Log.
Chkdsk /f removes ACLs that are no longer used and reports this in the Event Viewer -
Application Log.
Cluster (or block) Size
CHKDSK produces a report that shows the the block /cluster size
typically: "4096 bytes in each allocation unit."
Windows Command Prompt www.nubielab.com Page 11
When the cluster size is greater than 4 KB on an NTFS volume, none of the NTFS compression
functions are available.
Exit codes
0 No errors were found
1 Errors were found and fixed.
2 Could not check the disk, did not or could not fix errors.
Notes: Consider the time required to run Chkdsk to repair any errors that occur. Chkdsk times are
determined by the number of files on the volume and by the number of files in the largest folder.
Chkdsk performance 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.
Chkdsk is also available from the Recovery Console (with different parameters.)
Disk Errors
"The file system structure on the disk is corrupt and unusable" If you have disk corruption, run the drive manufacturers diagnostics:
Toshiba | Hitachi | ibm | Seagate/Maxtor/Freeagent | Western digital
CHKNTFS.exe
Check the NTFS file system with CHKDSK Syntax
CHKNTFS drive: [...]
CHKNTFS /C drive: [...]
CHKNTFS /X drive: [...]
CHKNTFS /t[:Time]
CHKNTFS /D
Key
drive : Specifies a drive letter.
/C : Check - schedules chkdsk to be run at the next reboot.
/X : Exclude a drive from the default boot-time check.
Excluded drives are not accumulated between command
invocations.
/T : Change the Autochk.exe initiation countdown time (time
in seconds)
If you don't specify Time: displays the current
countdown time.
/D : Restore the machine to the default behavior; all drives
are
checked at boot time and chkdsk is run on those that are
dirty.
This undoes the effect of the /X option.
If no switches are specified, CHKNTFS will display the status of the dirty bit for each drive.
/T option is new in Win XP
CHOICE.exe (Resource Kit/Standard Vista command) Accept user input to a batch file.
Choice allows single key-presses to be captured from the keyboard. Syntax
CHOICE [/C[:]choiceKeys] [/N] [/S] [/T[:]k,nn] [text]
Key
/C[:]choiceKeys : One or more keys the user can press.
Default is YN
/N : Do not display choiceKeys at end of prompt
string.
/S : case Sensitive.
/T[:]k,dd : Default the choice to k after dd seconds
text : Message string to display the choices
available
The Windows 2003 version has some slight differences:
CHOICE [/c [choiceKeys]] [/N] [/CS] [/t Timeout /d Choice]
[/m Text]
key
/C[:]choiceKeys : One or more keys the user can press.
Default is YN
/N : Do not display choiceKeys at end of prompt
string.
Windows Command Prompt www.nubielab.com Page 12
/CS : Case Sensitive.
/T dd : Timeout in dd seconds
/d choiceKey : Choice made on Timeout
/m text : Message string to describe the choices
available
ERRORLEVEL will return the numerical offset of choiceKeys.
Availability
Choice.com was originally supplied on the Windows 95 install CD, however there are some
issues with this version under NT - multiple concurrent invocations of CHOICE will clobber
each other. CHOICE.com will also burn a lot of CPU's when in a wait state.
The NT and 2000 Resource Kits contain CHOICE.EXE which behaves a lot better.
In Windows 2003 CHOICE became a built-in command so it is no longer in the resource kit.
Examples:
CHOICE /C:FH /M select [F] Floppy or [H] Hard drive
IF errorlevel 2 goto s_hard
IF errorlevel 1 goto s_floppy
Note the order of the IF statements above, IF errorlevel 1 will return TRUE for an errorlevel of 2
CHOICE can be used to set a specific %errorlevel%
for example to set the %errorlevel% to 6 :
ECHO 6| CHOICE /C:123456 /N >NUL
CMDKEY.exe (Windows 7)
Create, list or delete stored user names, passwords or credentials. Syntax
cmdkey [{/add:TargetName|/generic:TargetName}]
{/smartcard|/user:UserName [/pass:Password]}
[/delete{:TargetName|/ras}]
/list:TargetName
Key:
/add Add a user name and password to the list.
TargetName The computer or domain name that this entry
will be associated with.
/generic Add generic credentials to the list.
/smartcard Retrieve the credential from a smart card.
/user:UserName The user or account name to store with this
entry.
If UserName is not supplied, it will be
requested.
/pass:Password The password to store with this entry. If
Password is not supplied, it will be requested.
/delete: Delete a user name and password from the
list.
If TargetName is specified, that entry will
be deleted.
If /ras is specified, the stored remote
access entry will be deleted.
/list Display the list of stored user names and
credentials.
If TargetName is not specified, all stored
user names and credentials will be listed.
If more than one smart card is found, cmdkey will prompt the user to specify which one to use.
Once stored, passwords are not displayed.
Examples:
Display a list of stored user names and credentials:
cmdkey /list
Add a user name and password for user Kate to access computer Server01 with the password
passme, type:
cmdkey /add:server01 /user:Kate /pass:passme
Add a user name for user Kate to access computer Server01 and prompt for the password
whenever Server01 is accessed:
cmdkey /add:server01 /user:Kate
Delete the stored credential for remote access:
cmdkey /delete /ras
Delete the stored credential for Server01:
cmdkey /delete:Server01
COLOR Sets the default console foreground and background colours. Syntax
COLOR [background][foreground]
Colour attributes are specified by 2 of the following hex digits. Each digit can be any of the
following values:
0 = Black
Windows Command Prompt www.nubielab.com Page 13
8 = Gray
1 = Blue
9 = Light Blue
2 = Green
A = Light Green
3 = Aqua
B = Light Aqua
4 = Red
C = Light Red
5 = Purple
D = Light Purple
6 = Yellow
E = Light Yellow
7 = White
F = Bright White
If no argument is given, COLOR restores the colour to what it was when CMD.EXE started.
Colour values are assigned in the following order:
The DefaultColor registry value.
The CMD /T command line switch
The current colour settings when cmd was launched
The COLOR command sets ERRORLEVEL to 1 if an attempt is made to execute the COLOR
command with a foreground and background colour that are the same.
COMP.exe Compare two files (or sets of files). Display items which do not match. Syntax
COMP [pathname1] [pathname2] [/D] [/A] [/L] [/N=number]
[/C]
Key
pathname1 The path and filename of the first file(s)
pathname2 The path and filename of the second file(s)
/D Display differences in decimal format. (default)
/A Display differences in ASCII characters.
/L Display line numbers for differences.
/N=number Compare only the first X number of lines in the
file.
/C do a case insensitive string comparison
Running COMP with no parameters will result in a prompt for the 2 files and any options
To compare sets of files, use wildcards in pathname1 and pathname2 parameters.
When used with the /A option COMP is similar to the FC command but it displays the individual
characters that differ between the files rather than the whole line.
To compare files of different sizes, use /N= to compare only the first n lines (common portion of
each file.)
COMP will normally finish with a Compare more files (Y/N) prompt
to suppress this: ECHO n|COMP <options>
COPY Copy one or more files to another location Syntax
COPY source destination [options]
COPY source1 + source2.. destination [options]
Key
source : Pathname for the file or files to be copied.
/A : ASCII text file (default)
/B : Binary file copy - will copy extended characters.
destination : Pathname for the new file(s).
/V : Verify that the new files were written correctly.
/N : If at all possible, use only a short filename
(8.3) when creating
a destination file. This may be necessary when
copying between disks
Windows Command Prompt www.nubielab.com Page 14
that are formatted differently e.g NTFS and VFAT,
or when archiving
data to an ISO9660 CDROM.
/Z : Copy files in restartable mode. If the copy is
interrupted
part way through, it will restart if possible.
(use on slow networks)
/Y : Suppress confirmation prompt (Windows 2000 only)
/-Y : Enable confirmation prompt (Windows 2000 only)
Prompt to overwrite destination file
NT 4 will overwrite destination files without any prompt, Windows 2000 and above will prompt
unless the COPY command is being executed from within a batch script.
To force the overwriting of destination files under both NT4 and Windows2000 use the
COPYCMD environment variable:
SET COPYCMD=/Y
This will turn off the prompt in Win2000 and will be ignored by NT4 (which overwrites by
default)
Binary copies
"COPY /B ... " will copy all the files in binary mode , you can also put /B after any one file to
copy just that file in binary.
Combine files To combine files, specify a single file for the destination, but multiple files as the source. To
specify more than one file use wildcards or list the files with a + in between each
(file1+file2+file3)
When copying multiple files in this way the first file must exist or else the copy will fail, a
workaround for this is COPY null + file1 + file2 dest1
COPY will accept UNC pathnames
Copy from the console (accept user input)
COPY CON filename.txt
Then type the input text followed by ^Z (Control key & Z)
To do this in Powershell use the following function:
function copycon {
[system.console]::in.readtoend()
}
Examples:
In the current folder
COPY oldfile.doc newfile.doc
Copy from a different folder/directory:
COPY "C:\my work\some file.doc" "D:\New docs\newfile.doc"
Specify the source only, with a wildcard will copy all the files into the current directory:
COPY "C:\my work\*.doc"
Specify the source with a wildcard and the destination as a single file, this is generally only
useful with plain text files.
COPY "C:\my work\*.txt" "D:\New docs\combined.txt"
Quiet copy (no feedback on screen)
COPY oldfile.doc newfile.doc >nul
DEL Delete one or more files. Syntax
DEL [options] [/A:file_attributes] files_to_delete
Key
files_to_delete : This may be a filename, a list of files or
a Wildcard
options
/P Give a Yes/No Prompt before deleting.
/F Ignore read-only setting and delete anyway (FORCE)
/S Delete from all Subfolders (DELTREE)
/Q Quiet mode, do not give a Yes/No Prompt before deleting.
/A Select files to delete based on file_attributes
file_attributes:
R Read-only -R NOT Read-only
S System -S NOT System
H Hidden -H NOT Hidden
A Archive -A NOT Archive
Wildcards: These can be combined with part of a filename
* Match any characters
? Match any ONE character
Examples:
To delete HelloWorld.TXT
DEL HelloWorld.TXT
Windows Command Prompt www.nubielab.com Page 15
To delete "Hello Big World.TXT"
DEL "Hello Big World.TXT"
To delete all files that start with the letter A
DEL A*
To delete all files that end with the letter A
DEL *A.*
To delete all files with a .DOC extension
DEL *.DOC
To delete all read only files
DEL /a:R *
To delete all files including any that are read only
DEL /F *
Folders If a folder name is given instead of a file, all files in the folder will be deleted, but the folder
itself will not be removed.
Temporary Files You should clear out TEMP files on a regular basis - this is best done at startup when no
applications are running. To delete all files in all subfolders of C:\temp\ but leave the folder
structure intact: DEL /F /S /Q %TEMP%
When clearing out the TEMP directory it is not generally worthwhile removing the subfolders
too - they don't use much space and constantly deleting and recreating them can potentially
increase fragmentation within the Master File Table.
Deleting a file will not prevent third party utilities from un-deleting it again, however you can
turn any file into a zero-byte file to destroy the file allocation chain like this:
TYPE nul > C:\examples\MyFile.txt
DEL C:\examples\MyFile.txt
Undeletable Files Files are sometimes created with the very long filenames or reserved names: CON, AUX,
COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, NUL
To delete these use the syntax: DEL \\.\C:\somedir\LPT1
Alternatively SUBST a drive letter to the folder containing the file.
If a file (or folder) still appears to be 'undeletable' this is often caused by the indexing service.
Right click the file you need to delete, choose properties, advanced and untick "allow indexing"
you will then be able to delete the file.
To cure the problem permanently - Control Panel, Add/Remove programs, Win Accessories,
indexing service.
Delete Locked files (Typically IE temp files or the Offline cache)
This works on any version of NT, 2000 or XP
Close all applications
Open a command prompt
Click Start, and then Shut Down
Simultaneously press CTRL+SHIFT+ALT.
While you keep these keys pressed, click Cancel in the Shut Down Windows dialog box.
In the command prompt window, navigate to the cache location, and delete all files from the
folder (DEL /s)
At the command prompt, type explorer, and then press ENTER.
DELTREE
Previous versions of Windows had the DELTREE command that deletes all files and sub folders.
DEL /s will delete all files
RD /s will remove all files and folders including the root folder. :: Remove all files and subfolders but NOT the root folder
:: From tip 617 at JsiFAQ.com
@echo off
pushd %1
del /q *.*
for /f "Tokens=*" %%G in ('dir /B') do rd /s /q "%%G"
popd
Normally DEL will display a list of the files deleted, if Command Extensions are disabled; it will
instead display a list of any files it cannot find.
ERASE is a synonym for DEL
DELPROF (Resource Kit) Delete windows user profiles. Syntax
DELPROF [options]
Key
/Q Quiet, no confirmation.
/I Ignore errors and continue deleting.
/P Prompts for confirmation before deleting each
profile.
Windows Command Prompt www.nubielab.com Page 16
/C:\\computer_name
Delete profiles on a remote computer.
/D:Number_of_days
Only delete profiles that have been inactive for
'X' Number of days (or greater)
/R Delete roaming profile cache only ##
## = New in version 5.2 (XP resource kit)
Example:
delprof /D:14
DIR Display a list of files and subfolders Syntax
DIR [pathname(s)] [display_format] [file_attributes]
[sorted] [time] [options]
Key
[pathname] The drive, folder, and/or files to display,
this can include wildcards:
* Match any characters
? Match any ONE character
[display_format]
/P Pause after each screen of data.
/W Wide List format, sorted horizontally.
/D Wide List format, sorted by vertical
column.
[file_attributes] /A:
/A:D Folder /A:-D NOT Folder
/A:R Read-only /A:-R NOT Read-only
/A:H Hidden /A:-H NOT Hidden
/A:A Archive /A:-A NOT Archive
/A Show all files
several attributes may be combined e.g. /A:HD-R
[sorted] Sorted by /O:
/O:N Name /O:-N Name
/O:S file Size /O:-S file Size
/O:E file Extension /O:-E file Extension
/O:D Date & time /O:-D Date & time
/O:G Group folders first /O:-G Group folders last
several attributes may be combined e.g. /O:GEN
[time] /T: the time field to display & use for sorting
/T:C Creation
/T:A Last Access
/T:W Last Written (default)
[options]
/S include all subfolders.
/R Display alternate data streams. (Vista and above)
/B Bare format (no heading, file sizes or summary).
/L use Lowercase.
/Q Display the owner of the file.
/N long list format where filenames are on the far right.
/X As for /N but with the short filenames included.
/C Include thousand separator in file sizes.
/-C don't include thousand separator in file sizes.
/4 Display four-digit years
The switches above may be preset by adding them to an environment variable called DIRCMD.
For example: SET DIRCMD=/O:N /S
Override any preset DIRCMD switches by prefixing the switch with -
For example:
DIR *.* /-S
Upper and Lower Case filenames:
Filenames longer than 8 characters - will always display the filename with mixed case as
entered.
Filenames shorter than 8 characters - may display the filename in upper or lower case - this may
vary from one client to another (registry setting)
To obtain a bare DIR format (no heading or footer info) but retain all the details, pipe the output
of DIR into FIND, this assumes that your date separator is / DIR c:\temp\*.* | FIND "/"
Windows Command Prompt www.nubielab.com Page 17
FOR /f "tokens=*" %%G IN ('dir c:\temp\*.* ^| find "/"') DO echo
%%G
Normally DIR /b will return just the filename, however when displaying subfolders with DIR /b
/s the command will return a full pathname.
Checking filesize during a download (to monitor progress of a large download) TYPE file_being_downloaded >NUL
DIR file_being_downloaded
ECHO Display messages on screen, turn command-echoing on or off. Syntax
ECHO [ON | OFF]
ECHO [message]
Key
ON : Display each line of the batch on screen (default)
OFF : Only display the command output on screen
message : a string of characters to display
Type ECHO without parameters to display the current echo setting (ON or OFF).
In most batch files you will want ECHO OFF, turning it ON can be useful when debugging a
problematic batch script.
In a batch file, the @ symbol is the same as ECHO OFF applied to the current line only.
Normally a command is executed and takes effect from the next line onwards, @ is a rare
example of a command that takes effect immediately.
Command characters will normally take precedence over the ECHO statement
e.g. The redirection and pipe characters: & < > | ON OFF
To override this behaviour you can escape each command character with ^ as follows: ECHO Nice ^&Easy
ECHO Salary is ^> Commision
ECHO Name ^| Username ^| Expiry Date
ECHO:Off On Holiday
Echo text into a FILE
The general syntax is
Echo This is some Text > FileName.txt
ENDLOCAL
End localisation of environment changes in a batch file. Pass variables from one batch file to
another. Syntax
ENDLOCAL
If SETLOCAL is used to make variables 'local' to one batch script, then those variables will be
invisible to all other batch scripts unless explicitly passed using an ENDLOCAL & SET...
command.
If SETLOCAL is used without a corresponding ENDLOCAL then local environment variables
will be discarded when the batch file ends. Ending the cmd.exe session will discard all
Environment Variables both local and global.
Passing variables from one routine to another The CMD command processor always works on a line-by-line basis, so it will convert all
%variables% into their text values before executing any of the commands.
By putting ENDLOCAL & SET commands on a single line you are able to SET a variable just
before the localisation is ended by the ENDLOCAL command.
Examples: ::Sales.cmd
@Echo off
SETLOCAL
Set _item="Ice Cream Maker"
Set _price=450
ENDLOCAL & SET _return1=%_item%& SET _return2=%_price%
::Results.cmd
@Echo off
SETLOCAL
CALL Sales.cmd
Echo [%_return1%] will cost [%_return2%]
::SubDemo.cmd
@Echo off
SETLOCAL
CALL sub_products
Echo [%_return1%] will cost [%_return2%]
:sub_products
SETLOCAL
Windows Command Prompt www.nubielab.com Page 18
Set _item="Coffee Grinder"
Set _price=150
ENDLOCAL & SET _return1=%_item%& SET _return2=%_price%
Multiple SET commands may be added to pass multiple variables, just prefix each with an &
Be aware that any trailing spaces will be added to the variables value.
Improving readability The 'ENDLOCAL & SET' technique described above can become difficult to read if you have a
lot of SET commands all on the same line. This can be made easier to read if you first store all
the Set assignments in a single variable (_returns) as shown below (thanks to Ilya Bobyr for this
technique)
Set _returns=^
Set _return1=%_item%^&^
Set _return2=%_price%^&^
Set _return3=%_discount%^&^
Set _return4=%_delivery%
Endlocal & %_returns% In these examples we have used the variable names _return1, _return2 etc, but you can use any
names for the return variables, even re-use the exact same variable name inside and outside the
ENDLOCAL command (SET _price=%_price%)
EXIT Quit the current batch script, quit the current subroutine or quit the command processor
(CMD.EXE) optionally setting an errorlevel code. Syntax
EXIT [/B] [exitCode]
Key
/B When used in a batch script, this option will exit
only the script (or subroutine) but not CMD.EXE
exitCode Sets the %ERRORLEVEL% to a numeric number.
If quitting CMD.EXE, set the process exit code no.
You should never attempt to directly write to the %errorlevel% variable, (i.e. don't try anything
like SET errorlevel...) using the EXIT command provides a safe way to alter the value of the
built-in errorlevel variable.
Examples :: Exit if a required file is missing
@echo off
If not exist MyimportantFile.txt Exit /b
Echo The file was found
:: Set the error level to 5
@echo off
call :setError
echo %errorlevel%
goto :eof
:setError exit /B 5 To make this more flexible you can change the subroutine to set any errorlevel like this:
:setError exit /B %1
EXPAND Uncompress one or more compressed files. Syntax
EXPAND Source Destination
EXPAND -r Source Destination
EXPAND -r Source
Options
Source : Source filename or a wildcard
Destination : Destination filename or folder
-r : Rename the files
EXPAND
Uncompress one or more compressed files. Syntax
EXTRACT [options] CAB_file [filenames]
Key
CAB_file : Cabinet file
filenames : Name of the file to extract from the cabinet
Wild cards (*.*) (.) and multiple files are valid
options
/A Process ALL cabinets. (where CABs are linked)
/C If the CAB contains one file then /C will
copy from DMF disks
/D Display CAB directory
/E Extract all (use instead of *.* to extract all
files)
Windows Command Prompt www.nubielab.com Page 19
/L dir Location to place extracted files (default is
current folder)
/Y Overwrite files without any prompt
FC.exe Compare the contents of two files or sets of files. Display any lines which do NOT match. Syntax
FC /B pathname1 pathname2
FC [options] pathname1 pathname2
Key
/B : Perform a binary comparison.
options
/C : Do a case insensitive string comparison
/A : Displays only first and last lines for each set of
differences.
/U : Compare files as UNICODE text files.
/L : Compares files as ASCII text. (default)
/N : Display line numbers (ASCII only)
/LBn: Limit the number of lines that will be read, "n" sets a
maximum number
of mismatches after which the File Comparison will
abort (resync failed)
When FC aborts (resync failed) then "n" number of
mismatches will be shown.
/nnnn : Specify a number of consecutive lines that must match
after a mismatch.
This can be used to prevent the display of the two
files from getting
too out of sync
/T : Do not expand tabs to spaces.
/W : Compress white space (tabs and spaces) for
comparison.
To compare sets of files, use wildcards in pathname1 and pathname2 parameters.
Powershell also has an Alias FC for the Format-Custom command, therefore to run the 'old' FC
under powershell you need to explicitly run C:\windows\system32\fc.exe
To identify 2 identical files use this syntax: FC file1.txt file2.txt | FIND "FC: no dif" > nul
IF ERRORLEVEL 1 goto :s_files_are_different
Example:
If two files are compared and the four lines of text match as follows
1: different
2: same
3: same
4: different
Specifying /nnnn =2 the file compare will display the 4th line and continue
Specifying /nnnn =3 the file compare will halt at the 4th line (files too different)
Specifying /LB1 the file compare will halt after the first line
FIND
Search for a text string in a file & display all the lines where it is found. Syntax
FIND [/V] [/C] [/N] [/I] "string" [pathname(s)]
key
/V : Display all lines NOT containing the specified string.
/C : Count the number of lines containing the string.
/N : Display Line numbers.
/I : Ignore the case of characters when searching for the
string.
"string" : The text string to find (must be in quotes).
[pathname] : A drive, file or files to search.
If a [pathname] is not specified, FIND will prompt for text input or will accept text piped from
another command.
(use CTRL-Z to end manual text input)
Examples:
If names.txt contains the following: Joe Bloggs, 123 Main St, Dunoon
Arnold Jones, 127 Scotland Street, Edinburgh
Windows Command Prompt www.nubielab.com Page 20
To search for "Jones" in names.txt FIND "Jones" names.txt
---------- NAMES.TXT
Arnold Jones, 127 Scotland Street, Edinburgh
If you want to pipe a command into FIND use this syntax TYPE names.txt | FIND "Jones"
You can also redirect like this FIND /i "Jones" < names.txt >logfile.txt
To search a folder for files that contain a given search string FOR %G IN (*.txt) do (find /n /i "SearchWord" "%G")
FINDSTR Search for strings in files. Syntax
FINDSTR [options] [/F:file] [/C:string] [/G:file]
[string(s)] [pathname(s)]
Key
string Text to search for.
pathname(s) The file(s) to search.
/C:string Use string as a literal search string.
/G:file Get search string from a file (/ stands for
console).
/F:file Get a list of pathname(s) from a file (/ stands
for console).
/d dirlist Search a comma-delimited list of directories.
options may be any combination of the following switches:
/I Case-insensitive search.
/S Search subfolders.
/P Skip any file that contains non-printable characters
/L Use search string(s) literally.
/R Use search string(s) as regular expressions.(default)
/B Match pattern if at the Beginning of a line.
/E Match pattern if at the END of a line.
/X Print lines that match exactly.
/V Print only lines that do NOT contain a match.
/N Print the line number before each line that matches.
/M Print only the filename if a file contains a match.
/O Print character offset before each matching line.
/a color_attribute Display filenames in colour (2 hex digits)
When the search string contains multiple words (separated with spaces) then FINDSTR will
show show lines that contains any one word - (an OR of each word) - this behaviour is reversed
if the string argument is prefixed with /C.
Regular Expressions (Searching for patterns of text)
The FINDSTR syntax notation can use the following metacharacters which have special
meaning either as an operator or delimiter. . Wildcard: any character
* Repeat: zero or more occurances of previous character
or class
^ Line position: beginning of line
$ Line position: end of line
[class] Character class: any one character in set
[^class] Inverse class: any one character not in set
[x-y] Range: any characters within the specified range
\x Escape: literal use of metacharacter x
\<xyz Word position: beginning of
xyz\> Word position: end of word
Metacharacters are most powerful when they are used together. For example, the combination of
the wildcard character (.) and repeat (*) character is similar in effect to the filename wildcard
(*.*) .* Match any string of characters
The .* expression may be useful within a larger expression, for example f.*ing will match any
string beginning with F and ending with ing.
Examples:
Search for "granny" OR "Smith" in MyFile.txt.
FINDSTR "granny Smith" MyFile.txt
Search for "granny Smith" in MyFile.txt
FINDSTR /C:"granny Smith" MyFile.txt
This is effectively the same as the FIND command
Windows Command Prompt www.nubielab.com Page 21
To search every file in the current folder and all subfolders for the word "Smith",
regardless of upper/lower case use:
FINDSTR /s /i smith *.*
Note that /S will only search below the current directory
To find every line containing the word SMITH, preceeded by any number of spaces, and to
prefix each line found with a consecutive number:
FINDSTR /b /n /c:" *smith" MyFile.txt
Finding a string only if surrounded by the standard delimiters
To find the word "computer", but not the words "supercomputer" or "computerise":
FINDSTR "\<computer\>" MyFile.txt
Now assume you want to find not only the word "computer", but also any other words that begin
with the letters comp, such as "computerise" or "compete"
FINDSTR "\<comp.*" MyFile.txt
Example of a literal search
Searching a text file that contains the following
the quick brown fox
the darkbrown fox
the really *brown* fox
FINDSTR /r .*brown MyFile.txt
or
FINDSTR .*brown MyFile.txt
Will both match the word "brown" in all 3 lines
FINDSTR /L *brown* MyFile.txt
Will only match the last string
Using a script file
Multiple search criteria can be specified with a script file /G.
Multiple files to search can be specified with a source file /F.
When preparing a source or script file, place each item on a new line.
For example: to use the search criteria in Crit.txt to search the files listed in Files.txt and then
store the results in the file RESULTS.txt:
FINDSTR /g:Crit.txt /f:Files.txt> Results.txt
Errorlevel When an item is not found FINDSTR will return an errorlevel >0
Echo 12G6 |FindStr /R "[0-9]" If %ERRORLEVEL% EQU 0 echo The string contains one or more numeric characters Echo 12G6 |FindStr /R "[^0-9]" If %ERRORLEVEL% EQU 0 echo The string contains one or more non numeric characters Bugs In early versions of FindStr /F:file a path length of more than 80 chars will be truncated.
FOR /F Loop command: against a set of files - conditionally perform a command against each item. Syntax
FOR /F ["options"] %%parameter IN (filenameset) DO
command
FOR /F ["options"] %%parameter IN ("Text string to
process") DO command
Key
options:
delims=xxx The delimiter character(s) (default = a
space)
skip=n A number of lines to skip at the beginning of
the file.
(default = 0)
eol=; Character at the start of each line to
indicate a comment
The default is a semicolon ;
tokens=n Specifies which numbered items to read from
each line
(default = 1)
usebackq Specify `back quotes`:
- Use double quotes to quote long file names
in filenameset.
Windows Command Prompt www.nubielab.com Page 22
- Use single quotes for 'Text string to
process'
(useful if the text string contains double
quotes)
Filenameset A set of one or more files. Wildcards may be
used.
If (filenameset) is a period character (.)
then FOR will
loop through every file in the folder.
command The command to carry out, including any
command-line parameters.
%%parameter A replaceable parameter:
in a batch file use %%G (on the command line
%G)
FOR /F processing of a text file consists of reading the file, one line of text at a time and then
breaking the line up into individual items of data called 'tokens'. The DO command is then
executed with the parameter(s) set to the token(s) found.
By default, /F breaks up the line at each blank space " ", and any blank lines are skipped, this
default parsing behavior can be changed by applying one or more of the "options" parameters.
The option(s) must be contained within "a pair of quotes"
Within a FOR loop the visibility of FOR variables is controlled via SETLOCAL
EnableDelayedExpansion
Tokens tokens=2,4,6 will cause the second, fourth and sixth items on each line to be processed
tokens=2-6 will cause the second, third, fourth, fifth and sixth items on each line to be processed
tokens=* will cause all items on each line to be processed
tokens=3* will cause the 3rd and all subsequent items on each line to be processed
Each token specified will cause a corresponding parameter letter to be allocated.
If the last character in the tokens= string is an asterisk, then additional parameters are allocated
for all the remaining text on the line.
Delims More than one delimiter may be specified so a string like 'abcd+efg+hijk+lmno;pqr;stu+vwzyz'
can be broken up using "delims=;+".
You can use any character as a delimiter, but they are case sensitive.
If you don't specify delims it will default to "delims=<tab><space>"
n.b. some text editors will enter the TAB character as a series of spaces, specifying more than
one delimiter has been known to cause problems with some data sets.
usebackq
This option is useful when dealing with a filenameset that is a long filename containing spaces, it
allows you to put double quotes around the filename.
The backquote character ` is just below the ESC key on most keyboards.
eol The default end-of-line character is a semicolon ';' when the FOR command reads a text file (or
even a character string), any line that STARTS with the eol character will be ignored. In other
words it is treated as a comment.
Use eol=X to change the eol character to X.
Most often you will want to turn this feature off so that every line of your data file is processed,
in theory "eol=" should turn this feature off, but in practice this fails to work correctly so instead
set eol to some unusual character that you don't expect to ever be in the data file e.g. "eol=€" or
"eol=¬".
Examples Extracting data from this text file:
January,Snowy,02
February,Rainy,15
March,Sunny,25
FOR /F "tokens=1,3 delims=," %%G IN (weather.txt) DO @echo %%G %%H
The tricky part is splitting up each the line into the right tokens, in this case I'm splitting on the
comma character ',' this splits the line into 3 chunks of text and we pull out the first and third
items with "tokens=1,3"
token1 , token2 , token3
%%G <ignored> %%H
January 02
February 15
March 25
%%G is declared in the FOR statement and %%H is implicitly declared via the tokens= option.
You can specify up to 26 tokens via the tokens= line, provided this does not cause an attempt to
declare a parameter higher than the letter 'Z'.
FOR parameter names are global, so in complex scripts which call one FOR statement from
within another FOR statement you can refer to both sets of parameters. You cannot have more
than 26 parameters active at any one time.
Windows Command Prompt www.nubielab.com Page 23
Parse a text string: A string of text will be treated just like a single line of input from a file, the string must be
enclosed in double quotes (or single quotes with usebackq).
Echo just the date from the following string
FOR /F "tokens=4 delims=," %%G IN ("deposit,$4500,123.4,12-AUG-09") DO @echo Date
paid %%G
Parse the output of a command:
FOR /F %%G IN ('"C:\program Files\command.exe"') DO ECHO %%G
Parse the contents of a file:
FOR /F "tokens=1,2* delims=," %%G IN (C:\MyDocu~1\mytex~1.txt) DO ECHO %%G
FOR /F "usebackq tokens=1,2* delims=," %%G IN ("C:\My Documents\my textfile.txt") DO
ECHO %%G
Filenameset To specify an exact set of files to be processed, such as all .MP3 files in a folder including
subfolders and sorted by date - just use the DIR /b command to create the list of filenames ~ and
use this variant of the FOR command syntax.
FOR /F
Loop command: against the results of another command. Syntax
FOR /F ["options"] %%parameter IN ('command_to_process')
DO command
Key
options:
delims=xxx The delimiter character(s)
(default = a space)
skip=n A number of lines to skip at the beginning.
(default = 0)
eol=; Character at the start of each line to
indicate a comment
The default is a semicolon ;
tokens=n Specifies which numbered items to
read from each line
(default = 1)
usebackq Specify `back quotes`
the command_to_process is placed in `BACK
quotes`
instead of 'straight' quotes
command_to_process : The output of the 'command_to_process'
is
passed into the FOR parameter.
command : The command to carry out, including any
command-line parameters.
%%parameter : A replaceable parameter:
in a batch file use %%G (on the command line
%G)
FOR /F processing of a command consists of reading the output from the command one line at a
time and then breaking the line up into individual items of data or 'tokens'. The DO command is
then executed with the parameter(s) set to the token(s) found.
The FOR command is the answer to innumerable questions where you want to take the output of
some command, store it in a variable (%%G) then do something with the result.
For example the PING command returns serveral lines including one like:
Packets: Sent = 4, Recieved = 4, Lost = 0 (0% Loss),
To select that one line of output, you can search for the text "Loss" (which is always present),
then use the Tokens parameter to select the number of lost packets, here this is 0 but it will vary
each time you run the command.
set _ping_cmd=ping -n 5 127.0.0.1
FOR /f "tokens=4 delims=(=" %%G IN ('%_ping_cmd% ^|find "loss"') DO echo Result is
[%%G]
The tricky part is always splitting up the line of interest into the right tokens, in this case I'm
splitting on the characters '=' and '('
these two characters split the line into 5 chunks of text and we pull out the fourth one with
"tokens=4"
By default, /F breaks up the command output at each blank space, and any blank lines are
skipped.
You can override this default parsing behavior by specifying the "options" parameter. The
options must be contained within "quotes"
usebackq This option is useful when dealing with a command that already contains one or more straight
quotes.
The backquote character ` is just below the ESC key on most keyboards. See the FOR /F page
for other effects of usebackq.
Tokens tokens=2,4,6 will cause the second, fourth and sixth items on each line to be processed
tokens=2-6 will cause the second, third, fourth, fifth and sixth items on each line to be processed
tokens=* will cause all items on each line to be processed
tokens=3* will cause the 3rd and all subsequent items on each line to be processed
Windows Command Prompt www.nubielab.com Page 24
Each token specified will cause a corresponding parameter letter to be allocated.
If the last character in the tokens= string is an asterisk, then additional parameters are allocated
for all the remaining text on the line.
Delims More than one delimiter may be specified so a string like 'abcd+efg+hijk+lmno;pqr;stu+vwzyz'
can be broken up using "delims=;+".
You can use any character as a delimiter, but they are case sensitive.
If you don't specify delims it will default to "delims=<tab><space>"
Notice that some text editors will enter the TAB character as a series of spaces, specifying more
than one delimiter has been known to cause problems with some data sets.
eol The default end-of-line character is a semicolon ';' when the FOR command reads a text file (or
even a character string), any line that STARTS with the eol character will be ignored. In other
words it is treated as a comment.
Use eol=X to change the eol character to X.
Most often you will want to turn this feature off so that every line of your data file is processed,
in theory "eol=" should turn this feature off, but in practice this fails to work correctly so instead
set eol to some unusual character that you don't expect to ever be in the data file e.g. "eol=€" or
"eol=¬".
Examples:
To ECHO from the command line, the name of every environment variable. FOR /F "delims==" %G IN ('SET') DO @Echo %G
The same command with usebackq (Windows 2000 and above) FOR /F "usebackq delims==" %G IN (`SET`) DO @Echo %G
To put the Windows Version into an environment variable @echo off
::parse the VER command
FOR /F "tokens=4*" %%G IN ('ver') DO SET _version=%%G
:: show the result
echo %_version%
List all the text files in a folder FOR /F "tokens=*" %%G IN ('dir /b C:\docs\*.txt') DO echo %%G
FOR /F "tokens=*" %%G IN ('dir/b ^"c:\program files\*.txt^"')
DO echo %%G
In the example above the long filename has to be surrounded in "quotes"
these quotes have to be escaped using ^
The "tokens=*" has been added to match all parts of any long filenames returned by the DIR
command.
Although the above is a trivial example, being able to set %%G equal to each long filename in
turn could allow much more complex processing to be done.
More examples can be found on the Syntax / Batch Files pages and the other FOR pages below.
FOR Conditionally perform a command several times. syntax-FOR-Files
FOR %%parameter IN (set) DO command
syntax-FOR-Files-Rooted at Path
FOR /R [[drive:]path] %%parameter IN (set) DO command
syntax-FOR-Folders
FOR /D %%parameter IN (folder_set) DO command
syntax-FOR-List of numbers
FOR /L %%parameter IN (start,step,end) DO command
syntax-FOR-File contents
FOR /F ["options"] %%parameter IN (filenameset) DO
command
FOR /F ["options"] %%parameter IN ("Text string to
process") DO command
syntax-FOR-Command Results
FOR /F ["options"] %%parameter IN ('command to process')
DO command
The operation of the FOR command can be summarised as...
Take a set of data
Make a FOR Parameter %%G equal to some part of that data
Perform a command (optionally using the parameter as part of the command).
Repeat for each item of data
If you are using the FOR command at the command line rather than in a batch program, specify
%parameter instead of %%parameter.
FOR Parameters
The first parameter has to be defined using a single character, I tend to use the letter G.
e.g. FOR %%G IN ...
In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value
Windows Command Prompt www.nubielab.com Page 25
If this results in a single value then %%G is set equal to that value and the command is
performed.
If this results in a multiple values then extra parameters are implicitly defined to hold each.
These are automatically assigned in alphabetical order %%H %%I %%J ...(implicit parameter
definition)
Also if the parameter refers to a file, you can use an enhanced variable reference to quickly
extract the filename/path/date/size.
Example FOR /F "tokens=1-5" %%G IN ("This is a long sentence") DO @echo %%G %%H %%J
will result in the output
This is long
You can of course pick any letter of the alphabet other than %%G.
%%G is a good choice because it does not conflict with any of the pathname format letters (a, d,
f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit
parameters.
G > H > I > J > K > L > M
Using variables correctly Environment variables within a FOR loop are expanded at the beginning of the loop and won't
change until AFTER the end of the DO section.
The following example counts the files in the current folder, but %count% always returns 1:
@echo off
SET count=1
FOR /f "tokens=*" %%G IN ('dir /b') DO (
echo %count%:%%G
set /a count+=1)
To make this work correctly we must force the variable %count% to be evaluated during each
iteration, using the CALL :subroutine mechanism:
@echo off
SET count=1
FOR /f "tokens=*" %%G IN ('dir /b') DO (call :s_do_sums "%%G")
GOTO :eof
:s_do_sums
echo %count%:%1
set /a count+=1
GOTO :eof
Nested FOR commands
FOR commands can be nested FOR %%G... DO (for %%U... do ...)
when nesting commands choose a different letter for each part. you can then refer to both
parameters in the final DO command.
If Command Extensions are disabled, the FOR command will only support the basic syntax with
no enhanced variables:
FOR %%parameter IN (set) DO command [command-parameters]
FORFILES.exe (Resource Kit)
Select a file (or set of files) and execute a command on each file. Batch processing. Syntax
FORFILES [/p Path] [/m Mask] [/s] [/c Command] [/d [+ | -]
{dd/MM/yyyy | dd}]
Key
/p Path The Path to search (default=current folder)
/s Recurse into sub-folders
/C command The command to execute for each file.
Wrap the command string in double quotes.
Default = "cmd /c echo @file"
The Command variables listed below can also be
used in the
command string.
/D date Select files with a last modified date greater
than or
equal to (+), or less than or equal to (-),
the specified date using the "dd/MM/yyyy"
format;
or selects files with a last modified date
greater than
or equal to (+) the current date plus "dd" days,
or
less than or equal to (-) the current date minus
"dd" days.
A valid "dd" number of days can be any number in
the range of 0 - 32768.
"+" is taken as default sign if not specified.
Command Variables:
@file The name of the file.
@fname The file name without extension.
@ext Only the extension of the file.
@path Full path of the file.
Windows Command Prompt www.nubielab.com Page 26
@relpath Relative path of the file.
@isdir Returns "TRUE" if a file type is a directory,
and "FALSE" for files.
@fsize Size of the file in bytes.
@fdate Last modified date of the file.
@ftime Last modified time of the file.
To include special characters in the command line, use the hex code for the character in 0xHH
format (ex. 0x09 is theTAB character, 0x22 is the double quote " character.) so "C:\Program
Files\" becomes ^0x22C:\Program^ Files\^0x22
Internal CMD.exe commands must be preceded with "cmd /c".
If ForFiles finds one or more matches if will return %errorlevel% =0
If ForFiles finds no matches if will return %errorlevel% =1 and will print "ERROR: No files
found with the specified search criteria."
Very early versions of ForFiles use unix style -parameters, can only match dates newer than a
specified date and use the following command variables names: (which must be upper case)
@FILE, @FNAME_WITHOUT_EXT, @EXT, @PATH, @RELPATH, @ISDIR, @FSIZE,
@FDATE, @FTIME
Examples: Print a warning if the testfile is 5 days old or older:
C:\> forfiles /m testfile.txt /c "cmd /c echo file is too old" /d -5
Delete the testfile if it is is 5 days old or older:
C:\> forfiles /m testfile.txt /c "cmd /c Del testfile.txt " /d -5
Find .xls file that were last modified 30 days ago or longer
C:\> FORFILES /M *.xls /C "cmd /c echo @path was changed 30 days ago" /D -30
List the size of all .doc files:
C:\> FORFILES /S /M *.doc /C "cmd /c echo @fsize"
FORMAT.com Format a disk for use with Windows. Syntax
FORMAT drive: [/FS:file-system] [/V:label] [/Q] [size]
[/C]
Key
/FS:file-system The file system (FAT or NTFS).
The NTFS file system does not function on
floppy disks.
/V:label The volume label.
/Q Quick format.
/C Compression - files added to the new disk
will be compressed.
[size] may be defined either with /F:size or /A:size
/F:size size is the size of the floppy disk (720,
1.2, 1.44, 2.88, or 20.8).
/A:size Allocation unit size.
Default settings (via /F) are strongly
recommended for general use.
NTFS supports 512, 1024, 2048, 4096, 8192,
16K, 32K, 64K.
FAT supports 8192, 16K, 32K, 64K, 128K, 256K.
NTFS compression is not supported for
allocation units above 4096.
Example @echo off
Echo Warning this will reformat the entire D: disk!
PAUSE
format D: /FS:NTFS /x
FTYPE Display or change the link between a FileType and an executable program Syntax
FTYPE fileType=executable_path
FTYPE
FTYPE fileType
FTYPE fileType=
Key
fileType : The type of file
executable_path : The executable program including any
command line parameters
More than one file extension may be associated with the same File Type.
e.g. both the extension .JPG and the extension .JPEG may be associated with the File Type
"jpegfile"
File Types can be displayed in the Windows Explorer GUI under Options, File Types however
Windows Command Prompt www.nubielab.com Page 27
the naming used is not consistent e.g. the File Type "txtfile" is displayed in the GUI as "Text
Document"and "jpegfile" is displayed as "image/jpeg"
Several FileTypes can be linked to the same executable application.
FTYPE filetype will display the current executable program for that file type e.g. FTYPE
jpegfile.
FTYPE without any parameters will display all FileTypes and the executable program for each.
Defining command line parameters
It is almost always necessary to supply command line parameters so that when a document is
opened not only is the relevant application loaded into memory but the document itself also
loaded into the application. To make this happen the filename of the document must be passed
back to the application.
Command line parameters are exactly like batch file parameters, %0 is the executable program
and %1 will reference the document filename
so a simple command line might be:
MyApplication.exe "%1"
If any further parameters are required by the application they can be passed as %2, %3. To pass
ALL parameters to an application use %*. To pass all the remaining parameters starting with the
nth parameter, use %~n where n is between 2 and 9.
The FileType should always be created before making a File Association
For example:
FTYPE htmlfile="C:\PROGRA~1\Plus!\MICROS~1\iexplore.exe" -nohome
ASSOC .html=htmlfile
FTYPE pagemill.html=C:\PROGRA~1\Adobe\PAGEMI~1.0\PageMill.exe "%1"
ASSOC .html=pagemill.html
FTYPE rtffile="C:\Program Files\Windows NT\Accessories\WORDPAD.EXE" "%1"
ASSOC .rtf=rtffile
FTYPE word.rtf.8="C:\Program Files\Microsoft Office\Office\winword.exe" /n
ASSOC .rtf=word.rtf.8
Switching a File Association between multiple applications
If you have multiple applications that use the same file extension, the ASSOC command can be
used to switch the file extension between the different FileTypes.
Deleting a FileType
Specify executable_path=nothing and the FTYPE command will delete the executable_path
for that FileType.
For example:
FTYPE htmlfile=
Backup your FileTypes
FTYPE >backup_types.txt
ASSOC >backup_ext.txt
Restore your FileTypes from a Backup
FOR /F "tokens=* delims=" %G IN (backup_types.txt) DO FTYPE %G
FOR /F "tokens=* delims=" %G IN (backup_ext.txt) DO ASSOC %G
This will recreate the CLASS id's in the registry at HKey_Classes_Root\.<file extension>
If you put the commands above in a batch file change the %G to be %%G
Using File associations at the command line
If you have a file association between .DOC and Word for Windows then at a command prompt
you can open a document with any of the following commands:
Start "My Document.doc"
"Monthly Report.doc"
JULY.DOC
GOTO Direct a batch program to jump to a labelled line. Syntax
GOTO label
Key
label : a predefined label in the batch program. Each label
must
be on a line by itself, beginning with a colon.
Windows Command Prompt www.nubielab.com Page 28
To exit a batch script file or exit a subroutine specify GOTO:eof this will transfer control to the
end of the current batch file, or the end of the current subroutine.
Examples:
IF %1==12 GOTO MySubroutine
Echo the input was NOT 12
goto:eof
:MySubroutine
Echo the input was 12
goto:eof
Use a variable as a label
CHOICE /C:01 /m choose [Y]yes or [N]No
goto s_routine_%ERRORLEVEL%
:s_routine_0
Echo You typed Y for yes
goto:eof
:s_routine_1
Echo You typed N for no
goto:eof
Skip commands by using a variable as a :: comment (REM)
In this example the COPY command will only run if the parameter "Update" is supplied to the
batch
@echo off
setlocal
IF /I NOT %1==Update SET _skip=::
%_skip% COPY x:\update.dat
%_skip% echo Update applied
...
If Command Extensions are disabled GOTO will no longer recognise the :EOF label
"GOTO... how bad can it be??..." - XKCD
iCACLS.exe (2003 sp2, Vista)
Change file and folder permissions - display or modify Access Control Lists (ACLs) for files and
folders.
iCACLS resolves various issues that occur when using the older CACLS & XCACLS Syntax (files)
ICACLS FileName [/grant[:r] User:Permission[...]]
[/deny User:Permission[...]]
[/remove[:g|:d]] User[...]]
[/t] [/c] [/l] [/q]
[/setintegritylevel Level[...]]
Syntax (Store acls for all matching names into aclfile
for later use with /restore)
ICACLS name /save aclfile [/T] [/C] [/L] [/Q]
Syntax (restore folder)
ICACLS directory [/substitute SidOld SidNew [...]]
/restore aclfile [/C] [/L] [/Q]
Syntax (Change Owner)
ICACLS name /setowner user [/T] [/C] [/L] [/Q]
Syntax (Find items with an ACL that mentions a specific SID)
ICACLS name /findsid Sid [/T] [/C] [/L] [/Q]
Syntax (Find files whose ACL is not in canonical form or
with a length inconsistent with the ACE count.)
ICACLS name /verify [/T] [/C] [/L] [/Q]
Syntax (Replace ACL with default inherited acls for all matching
files)
ICACLS name /reset [/T] [/C] [/L] [/Q]
Key
/T Traverse all subfolders to match files/directories.
/C Continue on file errors (access denied) Error messages
are still displayed.
/L Perform the operation on a symbolic link itself, not its
target.
/Q Quiet - supress success messages.
/grant :r user:permission
Grant access rights, with :r, the permissions
will replace any previouly granted explicit permissions.
Otherwise the permissions are added.
Windows Command Prompt www.nubielab.com Page 29
/deny user:permission
Explicitly deny the specified user access rights.
This will also remove any explicit grant of the
same permissions to the same user.
/remove[:[g|d]] User
Remove all occurrences of User from the acl.
:g remove all granted rights to that User/Sid.
:d remove all denied rights to that User/Sid.
/setintegritylevel [(CI)(OI)]Level
Add an integrity ACE to all matching files.
level is one of L,M,H (Low Medium or High)
A Directory Inheritance option for the integrity ACE may
precede the level:
/inheritance:e|d|r
e - enable inheritance
d - disable inheritance and copy the ACEs
r - remove all inherited ACEs
user A user account, Group or a SID
/restore Apply the acls stored in ACLfile to the files in
directory
permission is a permission mask and can be specified in one
of two forms:
a sequence of simple rights:
F - full access
M - modify access
RX - read and execute access
R - read-only access
W - write-only access
a comma-separated list in parenthesis of specific
rights:
D - delete
RC - read control
WDAC - write DAC
WO - write owner
S - synchronize
AS - access system security
MA - maximum allowed
GR - generic read
GW - generic write
GE - generic execute
GA - generic all
RD - read data/list directory
WD - write data/add file
AD - append data/add subdirectory
REA - read extended attributes
WEA - write extended attributes
X - execute/traverse
DC - delete child
RA - read attributes
WA - write attributes
inheritance rights may precede either form and are
applied
only to directories:
(OI) - object inherit
(CI) - container inherit
(IO) - inherit only
(NP) - don't propagate inherit
Unlike many other command-line tools, iCACLS correctly preserves the canonical ordering of
ACE entries:
Explicit denials
Explicit grants
Inherited denials
Inherited grants
Access Control Lists apply only to files stored on an NTFS formatted drive, each ACL
determines which users (or groups of users) can read or edit the file. When a new file is created it
normally inherits ACL's from the folder where it was created.
Using iCACLS
To edit a file you must already have the "Change" ACL (or be the file's owner)
To use the iCACLS command to change the permissions of a file requires "FULL
Control" (or be the file's owner)
File "Ownership" will always override all ACL's - you always have Full Control over
files that you create.
Inherited folder permissions are displayed as: OI - Object inherit - This folder and files. (no inheritance
to subfolders)
CI - Container inherit - This folder and subfolders.
IO - Inherit only - The ACE does not apply to the current
file/directory
These can also be combined as folllows:
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
Windows Command Prompt www.nubielab.com Page 30
(OI) (IO) Files only.
So BUILTIN\Administrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F'
(Fullcontrol)
similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)
When cacls is applied to the current folder only there is no inheritance and so no output.
Bugs You can’t break existing inheritance of permissions with icacls, for that you need XCACLS.vbs.
In Windows Server 2003 SP2 there is a bug when attempting to use the /setowner switch, which
returns “Access denied”.
A limited release hotfix is available to resolve this issue (Q947870) alternatively use
SUBINACL
nb this bug is NOT present on Vista SP1 or Windows Server 2008.
Examples:
To backup the ACLs of every file in a directory type:
icacls * /save Myacl_backup.txt
Restore ACLS using a previously saved acl file:
icacls /restore Myacl_backup.txt
Change the Integrity Level (IL) of a file to High:
icacls MyReport.doc /setintegritylevel H
Grant the group FileAdmins Delete and Write DAC permissions to Sales_Folder:
icacls Sales_Folder /grant FileAdmins:(D,WDAC)
Propagate a new permission to all files and subfolders, without using inheritance:
(so if any of the subfolders contain specific permissions, those won't be overwritten)
icacls * /grant accountName:(NP)(RX) /T
IF Conditionally perform a command. File syntax
IF [NOT] EXIST filename command
IF [NOT] EXIST filename (command) ELSE (command)
String syntax
IF [/I] [NOT] item1==item2 command
IF [/I] item1 compare-op item2 command
IF [/I] item1 compare-op item2 (command) ELSE (command)
Error Check Syntax
IF [NOT] DEFINED variable command
IF [NOT] ERRORLEVEL number command
IF CMDEXTVERSION number command
key
item May be a text string or an environment variable
a variable may be modified using either
Substring syntax or Search syntax
command The command to perform
NOT perform the command if the condition is false.
== perform the command if the two strings are equal.
/I Do a case Insensitive string comparison.
compare-op May be one of
EQU : Equal
NEQ : Not equal
LSS : Less than <
LEQ : Less than or Equal <=
GTR : Greater than >
GEQ : Greater than or equal >=
This 3 digit syntax is necessary because the >
and <
symbols are recognised as redirection operators
IF ERRORLEVEL n statements should be read as IF Errorlevel >= number
i.e.
IF ERRORLEVEL 0 will return TRUE when the errorlevel is 64
An alternative and often better method of checking Errorlevels is to use the string syntax along
with the %ERRORLEVEL% variable:
Windows Command Prompt www.nubielab.com Page 31
IF %ERRORLEVEL% GTR 0 Echo An error was found
IF %ERRORLEVEL% LSS 0 Echo An error was found
IF %ERRORLEVEL% EQU 0 Echo No error found
IF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE (Echo An error was found)
IF %ERRORLEVEL% EQU 0 Echo No error found || Echo An error was found
Note some errors are negative numbers.
When working with errorlevels in a batch file it's a good idea to also use SETLOCAL so that the
%ERRORLEVEL% variable is reset each time the batch file runs.
IF EXIST filename will return true if the file exists (this is not case sensitive).
Examples: IF EXIST C:\install.log (echo complete) ELSE (echo failed)
IF DEFINED _department ECHO Got the department variable
IF DEFINED _commission SET /A _salary=%_salary% + %_commission%
IF CMDEXTVERSION 1 GOTO start_process
IF %ERRORLEVEL% EQU 2 goto sub_problem2
Does %1 exist?
To test for the existence of a command line parameter - use empty brackets like this
IF [%1]==[] ECHO Value Missing
or
IF [%1] EQU [] ECHO Value Missing
In the case of a variable that may be NULL - a null variable will remove the variable definition
altogether, so testing for NULLs becomes easy:
IF NOT DEFINED _example ECHO Value Missing
IF DEFINED will return true if the variable contains any value (even if the value is just a space)
Test the existence of files and folders IF EXIST name - will detect the existence of a file or a folder - the script empty.cmd will show if
the folder is empty or not.
Brackets
You can improve the readability of a batch script by writing a complex IF...ELSE command over
several lines using brackets
e.g.
IF EXIST filename (
del filename
) ELSE (
echo The file was not found.
)
The IF statement does not use any great intelligence when evaluating Brackets, so for example
the command below will fail:
IF EXIST MyFile.txt (ECHO Some(more)Potatoes)
This version will work:
IF EXIST MyFile.txt (ECHO Some[more]Potatoes)
Testing Numeric values Do not use brackets or quotes when comparing numeric values
e.g.
IF (2) GEQ (15) echo "bigger"
or
IF "2" GEQ "15" echo "bigger"
These will perform a character comparison and will always echo "bigger"
however the command
IF 2 GEQ 15 echo "bigger"
Will perform a numeric comparison and works as expected - notice that this behaviour is exactly
opposite to the SET /a command where quotes are required.
The examples here all use GEQ, but this applies equally to all the compare-op operators: EQU,
NEQ, LSS, LEQ, GTR, GEQ
when comparing numbers as a string "026" > "26"
Wildcards Wildcards are not supported by IF, so %COMPUTERNAME%==SS6* will not match SS64
A workaround is to retrieve the substring and compare just those characters:
SET _prefix=%COMPUTERNAME:~0,3%
IF %_prefix%==SS6 GOTO they_matched
Pipes When piping commands, the expression is evaluated from left to right, so
IF... | ... is equivalent to (IF ... ) | ...
you can also use the explicit syntax IF (... | ...)
ERRORLEVEL To deliberately raise an ERRORLEVEL in a batch script use the EXIT /B command.
It is possible (though not a good idea) to create a string variable called %ERRORLEVEL% (user
variable)
if present such a variable will prevent the real ERRORLEVEL (a system variable) from being
used by commands such as ECHO and IF.
To test for the existence of a user variable use SET errorlevel, or IF DEFINED ERRORLEVEL
If Command Extensions are disabled IF will only support direct comparisons: IF ==, IF EXIST,
IF ERRORLEVEL
also the system variable CMDEXTVERSION will be disabled.
Windows Command Prompt www.nubielab.com Page 32
IPCONFIG Configure IP (internet protocol configuration) Syntax
IPCONFIG /all Display full configuration information.
IPCONFIG /release [adapter]
Release the IP address for the specified
adapter.
IPCONFIG /renew [adapter]
Renew the IP address for the specified
adapter.
IPCONFIG /flushdns Purge the DNS Resolver cache.
IPCONFIG /registerdns Refresh all DHCP leases and re-register
DNS names.
IPCONFIG /displaydns Display the contents of the DNS Resolver
Cache.
IPCONFIG /showclassid adapter
Display all the DHCP class IDs allowed
for adapter.
IPCONFIG /setclassid adapter [classid]
Modify the dhcp class id.
If the Adapter name contains spaces, use quotes: "Adapter Name"
wildcard characters * and ? allowed, see the examples below
The default is to display only the IP address, subnet mask and default gateway for each adapter
bound to TCP/IP.
For Release and Renew, if no adapter name is specified, then the IP address leases for all
adapters bound to TCP/IP will be released or renewed.
For Setclassid, if no ClassId is specified, then the ClassId is removed. Examples:
> ipconfig ... Show information.
> ipconfig /all ... Show detailed information
> ipconfig /renew ... renew all adapters
> ipconfig /renew EL* ... renew any connection that
has its
name starting with EL
> ipconfig /release *Con* ... release all matching
connections,
eg. "Local Area Connection
1" or
"Local Area Connection
2"
> ipconfig /setclassid "Local Area Connection" TEST
... set the DHCP class ID for
the
named adapter to = TEST
KILL (Resource kit) Remove a running process from memory. Syntax
KILL [option] process_id
KILL [option] task_name
KILL [option] window_title
Option
-f Force process kill
Note: Kill -f basically just nukes the process from existence, potentially leaking a lot of memory
and losing any data that the process hadn't committed to disk yet. It is there for worst case
scenarios - when you absolutely must end the process now, and don't care whether proper
cleanup gets done or not.
In WindowsXP, KILL is replaced with the superior TASKKILL - Allowing you to specify a
remote computer, different user account etc - for more details run TASKKILL /?
LOGOFF.exe (Resource Kit) Log a user off. Syntax
LOGOFF [/f] [/n]
Key
/f Force running processes to close, but will ask for user
confirmation.
Windows Command Prompt www.nubielab.com Page 33
The user will not be asked to save unsaved data.
/n Force running processes to close without confirmation.
The user will be prompted to save unsaved data.
By default LOGOFF will ask for user confirmation and prompt to save unsaved data.
Windows security log events Logon Event IDs 528 and 540 = successful logon
Logoff Event ID 538 = logoff
Logon and logoff events also specify a Logon Type code:
Logon Type 2 – Interactive - Log on at the local keyboard / screen (see the event description for
a computer name).
Logon Type 3 – Network - connections to shared folders or printers, over-the-network logons,
IIS logons( but not basic authentication)
Logon Type 4 – Batch - The Scheduled Task service creates a new logon session for each task.
Logon Type 5 – Service - Each service is configured to run as a specified user account.
Logon Type 7 – Unlock- a password protected screen saver.
Logon Type 8 – NetworkCleartext - a network logon like logon type 3 but where the password
was sent over the network in clear text.
Logon Type 9 – NewCredentials - If you use RunAs /netonly and records the logon event with
logon type 2.
Logon Type 10 – RemoteInteractive - Terminal Services, Remote Desktop or Remote
Assistance.
Logon Type 11 – CachedInteractive - mobile users not connected to the network connecting with
cached credentials.
MAPISEND (Back Office/Exchange Resource kit) Send email from the command line. Syntax
MAPISEND -u "profile" -p password
-r recipient -s "subject" -m text message [options]
MAPISEND -u "profile" -p password
-r recipient -s "subject" -t text_file [options]
options
-i interactive login (prompts for profile and password)
-c cc: list
-f File Attachment - path and file name(s)
-v generates verbose output (an 8 line summary of the
message)
"profile" is the profile name (user mailbox) of sender
"subject" is the subject line
"recipient" is one or more recipient(s)
If more than one recipient - separate with ';' these must not be
ambiguous in the default address book.
Mapisend requires MAPI - i.e the MS Outlook client needs to be installed.
Examples mapisend -u "MS Exchange Settings" -p MyPassword -r
billg@sun.com -s "Subject" -m "Test message text"
mapisend -u "MS Exchange Settings" -p MyPassword -r billg@hp.com
-s "Subject" -t c:\MyMail.txt >> c:\mail.log
MEM Display memory usage. Syntax
MEM
MEM /C
MEM /D
MEM /P
Key
/P List programs in memory
with the memory address and size of each
/D List Programs(as /P) and also Devices
/C List programs in conventional memory and
list programs in upper memory
MEM will only display details about the current CMD shell environment, programs running in a
separate shell (or WIN32 programs) will not be listed - so it won't tell you anything about total
memory usage.
MD Make Directory - Creates a new folder. Syntax
MD [drive:]path
Key
Windows Command Prompt www.nubielab.com Page 34
The path can consist of any valid characters up to the
maximum path length available
You should avoid using the following characters in folder names - they are known to cause
problems
© ® " - & ' ^ ( ) and @
also many extended characters may not be recognised by older 16 bit windows applications.
The maximum length of a full pathname (folders and filename) under NTFS or FAT is 260
characters.
Folder names are not case sensitive, but only folder names longer than 8 characters will always
retain their case, as typed.
For Example C:\temp> MD MyFolder
Make several folders with one command C:\temp> MD Alpha Beta Gamma
will create
C:\temp\Alpha\
C:\temp\Beta\
C:\temp\Gamma\
Make an entire path MD creates any intermediate directories in the path, if needed.
For example, assuming \utils does not exist then: MD \utils\downloads\Editor
is the same as:
md \utils
cd \utils
md downloads
cd downloads
md Editor
for long filenames include quotes
MD "\utils\downloads\Super New Editor"
You cannot create a folder with the same name as any of the following devices:
CON, PRN, LPT1, LPT2 ..LPT9, COM1, COM2 ..COM9
This limitation ensures that redirection to these devices will always work.
If you plan to copy data onto CDROM avoid folder trees more than 8 folders deep
MKDIR is a synonym for MD
MOVE Move a file from one folder to another 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:
/Y Suppress confirmation prompt.
/-Y Enable confirmation prompt.
Both Source and Target may be either a folder or a single file.
The source may include wildcards (but not the destination).
Under Windows 2000 and above, 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 use the COPYCMD environment variable:
SET COPYCMD=/Y
Using the COPYCMD variable has the advantage that the command will still work in early
versions of windows (e.g. NT4) which don't support the /Y option (they overwrite by default).
Examples:
In the current folder
MOVE oldfile.wp newfile.doc
Full path specified
MOVE g:\department\oldfile.wp "c:\Files to Convert\newfile.doc"
Specify the drive and filename (assumes the current folder on both drives is correct)
MOVE a:oldfile.wp c:newfile.doc
Specify source only (will copy the file to current folder, keeping the same filename)
MOVE g:\department\oldfile.wp
Quiet move (no feedback on screen)
MOVE oldfile.wp newfile.doc >nul
Windows Command Prompt www.nubielab.com Page 35
MSG.exe Send a pop-up message to a user. The 'Home' editions of Windows don’t include MSG. Syntax
MSG username [options] [message]
MSG sessionname [options] [message]
MSG sessionid [options] [message]
MSG @filename [options] [message]
MSG * [options] [message]
Options
/SERVER:servername The server to contact (default is
current).
/TIME:seconds Time delay to wait for receiver to
acknowledge msg.
/V Verbose, display extra information.
/W Wait for response from user, useful with
/V.
If no message text to send is specified, MSG will prompt for it
(also reads from stdin)
@filename identifies a file containing a list of usernames,
sessionnames or sessionids to send the message to.
* will send the message to all sessions on the server.
e.g. use this for Terminal Server/Citrix shutdown messages.
MV.exe (Resource Kit)
Move File - Copy a file to another location even if the file is in use (Locked) Syntax
MV /x /d source destination
Key
The first file name is the file to be copied and the second
the destination pathname.
/d : does not copy the file until reboot time
allows in-use files to be replaced
/x : Prevents the default action that will otherwise create a
folder called "deleted" containing a copy of the
original file.
Note that you must use a FULL pathname to each file.
The NT resource kit contains 2 versions of MV.EXE - a posix version and a Windows NT
version - they are not the same!
The /d option is not available with the posix version of mv, but if you prefer, you can do a file
replace at boot time by manually updating the registry (which is all MV.exe does)
Start the registry editor (regedt32.exe not regedit.exe)
Move to HKLM\SYSTEM\CurrentControlSet\Control\Session Manager
Double click on
PendingFileRenameOperations
(if it does not exist - create of type multi_str )
On the first line is the name of the new file with \??\ in front,
e.g.
\??\d:\temp\ntfs.sys
On the second line is the file to replaced with !\??\ in front,
e.g.
!\??\c:\winnt\system32\drivers\ntfs.sys
Click OK
So the complete Multi-String Data would appear like:
\??\d:\temp\ntfs.sys
!\??\c:\winnt\system32\drivers\ntfs.sys
Once the reboot is complete and the file replaced the PendingFileRenameOperations value will
be deleted from the registry
NETSH (Network Shell) Configure Network Interfaces, Windows Firewall, Routing & remote access. Syntax
NETSH [Context] [sub-Context] command
Windows Command Prompt www.nubielab.com Page 36
Key
The contexts and commands available vary by platform, the list
below is for Windows 2008.
Use interactive mode/help (described below) to check the
commands available on your machine.
= add - Add a configuration entry to a list of
entries.
netsh add helper - Install the specified helper DLL
= advfirewall - Change the 'netsh advfirewall' context.
netsh advfirewall consec ? - Display a list of
commands.
netsh advfirewall consec add - Add a new connection
security rule.
netsh advfirewall consec delete - Delete all matching
connection security rules.
netsh advfirewall consec dump - Display a
configuration script.
netsh advfirewall consec set - Set new values for
properties of an existing rule.
netsh advfirewall consec show - Display a specified
connection security rule.
netsh advfirewall dump Create a script that contains the
current configuration.
If saved to a file, this can be used
to restore the configuration settings.
netsh advfirewall export path\filename - Export the current
policy to the specified file.
netsh advfirewall import path\filename - Import policy from the
specified file.
netsh advfirewall firewall add - Add a new inbound or
outbound firewall rule.
netsh advfirewall firewall delete - Delete all matching
inbound rules.
netsh advfirewall firewall dump - Display a
configuration script.
netsh advfirewall firewall set - Set new values for
properties of a existing rule.
netsh advfirewall firewall show - Display a specified
firewall rule.
netsh advfirewall monitor delete - Delete all matching
security associations.
netsh advfirewall monitor dump - Display a
configuration script.
netsh advfirewall monitor show - Show all matching
security associations.
netsh advfirewall reset - Reset to factory settings
(Firewall=ON)
netsh advfirewall set allprofiles - Set properties in all
profiles.
netsh advfirewall set currentprofile - Set properties in the
active profile.
netsh advfirewall set domainprofile - Set properties in the
domain profile.
netsh advfirewall set global - Set the global
properties.
netsh advfirewall set privateprofile - Set properties in the
private profile.
netsh advfirewall set publicprofile - Set properties in the
public profile.
netsh advfirewall show allprofiles - Display properties for
all profiles.
netsh advfirewall show currentprofile - Display properties for
the active profile.
netsh advfirewall show domainprofile - Display properties for
the domain properties.
netsh advfirewall show global - Display the global
properties.
netsh advfirewall show privateprofile - Display properties for
the private profile.
netsh advfirewall show publicprofile - Display properties for
the public profile.
netsh advfirewall show store - Display the policy store
for the current interactive session.
=bridge - Change to the 'netsh bridge' context.
netsh bridge dump - Display a configuration script.
netsh bridge install - Install the component
corresponding to the current context.
netsh bridge set - Set configuration information.
netsh bridge show - Display information.
Windows Command Prompt www.nubielab.com Page 37
netsh bridge uninstall - Remove the component corresponding
to the current context.
=delete - Delete a configuration entry from a list of
entries.
netsh delete helper Remove the specified helper DLL from
netsh.
Note that after a helper is removed, it is no longer supported
by netsh.
=dhcpclient - Change to the 'netsh dhcpclient' context.
netsh dhcpclient list - List all the commands
available.
netsh dhcpclient trace enable - Enable tracing for DHCP
client and DHCP QEC.
netsh dhcpclient trace disable - Disable tracing for DHCP
client and DHCP QEC.
=dump - Display a configuration script.
netsh dump - Create a script that contains the current
configuration.
If saved to a file, this can be used to restore
the configuration settings.
=exec - Run a script file.
exec - Load a script file and run it.
=firewall - Change to the 'netsh firewall' context.
netsh firewall add - Add firewall configuration.
netsh firewall delete - Delete firewall
configuration.
netsh firewall dump - Display a configuration
script.
netsh firewall reset - Reset firewall configuration
to default.
netsh firewall set allowedprogram - Set firewall allowed program
configuration.
netsh firewall set icmpsetting - Set firewall ICMP
configuration.
netsh firewall set logging - Set firewall logging
configuration.
netsh firewall set multicastbroadcastresponse - Set firewall
multicast/broadcast response configuration.
netsh firewall set notifications - Set firewall notification
configuration.
netsh firewall set opmode - Set firewall operational
configuration.
netsh firewall set portopening - Set firewall port
configuration.
netsh firewall set service - Set firewall service
configuration.
netsh firewall show allowedprogram - Show firewall allowed
program configuration.
netsh firewall show config - Show firewall
configuration.
netsh firewall show currentprofile - Show current firewall
profile.
netsh firewall show icmpsetting - Show firewall ICMP
configuration.
netsh firewall show logging - Show firewall logging
configuration.
netsh firewall show multicastbroadcastresponse - Show firewall
multicast/broadcast response configuration.
netsh firewall show notifications - Show firewall notification
configuration.
netsh firewall show opmode - Show firewall operational
configuration.
netsh firewall show portopening - Show firewall port
configuration.
netsh firewall show service - Show firewall service
configuration.
netsh firewall show state - Show current firewall
state.
=help - Display a list of netsh commands.
netsh help
=http - Change to the 'netsh http' context.
netsh http add - Add a configuration entry to a
table.
netsh http delete - Delete a configuration entry from a
table.
netsh http dump - Display a configuration script.
netsh http flush - Flushe internal data.
netsh http show - Display information.
=interface - Change to the 'netsh interface' context.
netsh interface 6to4 + Change to the 'netsh interface
6to4' context.
Windows Command Prompt www.nubielab.com Page 38
netsh interface add - Add a configuration entry to a
table.
netsh interface delete - Delete a configuration entry
from a table.
netsh interface dump - Display a configuration script.
netsh interface ipv4 + Change to the 'netsh interface
ipv4' context.
netsh interface ipv6 + Change to the 'netsh interface
ipv6' context.
netsh interface isatap + Change to the 'netsh interface
isatap' context.
netsh interface portproxy + Change to the 'netsh interface
portproxy' context.
netsh interface reset - Reset information.
netsh interface set - Set configuration information.
netsh interface show - Display information.
netsh interface tcp + Change to the 'netsh interface
tcp' context.
netsh interface teredo + Change to the 'netsh interface
teredo' context.
The following sub-contexts are available:
6to4 ipv4 ipv6 isatap portproxy tcp teredo
=ipsec - Change to the 'netsh ipsec' context.
netsh ipsec dump - Display a configuration script.
netsh ipsec dynamic add - Add policy, filter, and
actions to SPD.
netsh ipsec dynamic delete - Delete policy, filter, and
actions from SPD.
netsh ipsec dynamic dump - Display a configuration
script.
netsh ipsec dynamic set - Modifiy policy, filter, and
actions in SPD.
netsh ipsec dynamic show - Display policy, filter, and
actions from SPD.
netsh ipsec static add - Create new policies and
related information.
netsh ipsec static delete - Delete policies and related
information.
netsh ipsec static dump - Display a configuration
script.
netsh ipsec static exportpolicy - Export all the policies from
the policy store.
netsh ipsec static importpolicy - Import the policies from a
file to the policy store.
netsh ipsec static set - Modify existing policies and
related information.
netsh ipsec static show - Display details of policies
and related information.
=lan - Change to the 'netsh lan' context.
netsh lan add - Add a configuration entry to a table.
netsh lan delete - Delete a configuration entry from a
table.
netsh lan dump - Display a configuration script.
netsh lan export - Save LAN profiles to XML files.
netsh lan reconnect - Reconnect on an interface.
netsh lan set - Configure settings on interfaces.
netsh lan show - Display information.
=nap - Change to the 'netsh nap' context.
netsh nap client + Change to the 'netsh nap client'
context.
netsh nap dump - Display a configuration script.
netsh nap hra + Change to the 'netsh nap hra'
context.
netsh nap reset - Reset configuration.
netsh nap show - Show configuration and state
information.
=netio - Change to the 'netsh netio' context.
netsh netio add - Add a configuration entry to a
table.
netsh netio delete - Delete a configuration entry from a
table.
netsh netio dump - Display a configuration script.
netsh netio show - Display information.
=ras - Change to the 'netsh ras' context. (Remote
Access Server)
netsh ras aaaa - Change to the 'netsh ras aaaa'
context.
netsh ras add - Add items to a table.
netsh ras delete - Remove items from a table.
netsh ras diagnostics - Change to the 'netsh ras diagnostics'
context.
netsh ras dump - Display a configuration script.
netsh ras ip - Change to the 'netsh ras ip' context.
Windows Command Prompt www.nubielab.com Page 39
netsh ras ipv6 - Change to the 'netsh ras ipv6'
context.
netsh ras set - Set configuration information.
netsh ras show - Display information.
=rpc - Change to the 'netsh rpc' context. (RPC
firewall filter)
netsh rpc add - Create an Add list of subnets.
netsh rpc delete - Create a Delete list of subnets.
netsh rpc dump - Display a configuration script.
netsh rpc filter - Change to the 'netsh rpc filter'
context.
netsh rpc reset - Reset the selective binding settings
to 'none' (listen on all interfaces).
netsh rpc show - Display the selective binding state
for each subnet on the system.
=set - Update configuration settings on a remote
machine.
netsh set machine [name=] [user=][[DomainName\]UserName]
[pwd=][Password | *]
If a machine name is not specified, the local machine is used.
A username and password cannot be used to connect to the local
machine.
=show - Display information.
netsh show alias - List all defined aliases.
netsh show helper - List all the top-level helpers.
=winhttp - Change to the 'netsh winhttp' context.
netsh winhttp dump - Display a configuration script.
netsh winhttp import - Import WinHTTP proxy settings.
netsh winhttp reset - Reset WinHTTP settings.
netsh winhttp set - Configure WinHTTP settings.
netsh winhttp show - Display currents settings.
=winsock - Change to the 'netsh winsock' context.
netsh winsock audit - Display a list of Winsock LSPs
that have been installed and removed.
netsh winsock dump - Display a configuration script.
netsh winsock remove - Remove a Winsock LSP from the
system.
netsh winsock reset - Reset the Winsock Catalog to a
clean state.
netsh winsock show - Display information.
netsh - Interactive mode
In interactive mode, switch context by typing any context name: advfirewall, bridge, firewall,
http, interface, ipsec.. etc
list commands with ? exit interactive mode with Quit or Exit.
To view help for any command, type the command, followed by a space and ?
The syntax on this page is based on Windows 2008, for backwards compatibility with XP dns is
an alias for dnsserver, ip is an alias for ipv4
Examples: Install ipmontr.dll:
C:\> netsh advfirewall net add helper ipmontr.dll
Export the fiewall policy:
C:\> netsh advfirewall export "c:\advfirewallpolicy.wfw"
Show TCP/IP settings
C:\> netsh interface ip show config
Set a static IP address (e.g. for a laptop)
C:\> Netsh interface ip set address name="Local Area Connection" source=static
addr=192.168.0.10 mask=255.255.255.0 gateway=192.168.0.1 gwmetric=1
Set a dynamic IP address with DHCP
C:\> Netsh interface ip set address name="Local Area Connection" source=dhcp
Add multiple DNS servers:
C:\> Netsh interface ipv4 add dns "Local Area Connection" 10.0.0.1
C:\> Netsh interface ipv4 add dns "Local Area Connection" 10.0.0.3 index=2
index=2 adds the IP as a secondary dns server.
Set a static DNS server address:
C:\> Netsh interface ip set dns name="Local Area Connection" source=static addr=192.168.0.2
register=none
Set a dynamic DNS server address with DHCP:
C:\> netsh interface ip set dns name="Local Area Connection" source=dhcp
Set a static address for the WINS server:
C:\> Netsh interface ip set wins name="Local Area Connection" source=static
addr=192.168.100.3
To configure WINS from DHCP:
C:\> Netsh interface ip set wins name="Local Area Connection" source=dhcp
Windows Command Prompt www.nubielab.com Page 40
Backup the local DHCP server configuration to a file:
C:\> netsh dump dhcp > C:\backupDHCPconfig.dat
You can use this backup file to recreate the DHCP server with Netsh .
Work against a remote machine:
C:\> netsh set machine server64
Backup the current network interface configuration to a file:
C:\> netsh dump interface > c:\backupInterfaceConfig.dat
Restore network interface configuration from a file:
C:\> netsh exec c:\backupInterfaceConfig.dat
Run Netsh from Powershell (returns a Text object you can manipulate)
PS C:\> $myFWstate=netsh firewall show state
PS C:\> $myFWstate -match "disable"
Disable Network auto-tuning (certain routers and networking devices perform better with this
off.)
PS C:\> netsh interface tcp set global autotuning=disabled
Enable Network auto-tuning (certain routers and networking devices perform better with this
on.)
PS C:\> netsh interface tcp set global autotuning=normal
NBTSTAT.exe
Display protocol statistics and current TCP/IP connections using NBT (NetBIOS over TCP/IP). Syntax
By Name
NBTSTAT -a Remote_host_Name [options] [interval]
By IP address
NBTSTAT -A IP_address [options] [interval]
Key
-a (adapter status) List the remote machine's name table
given its name
-A (Adapter status) List the remote machine's name table
given its IP address
-c (cache) List NBT's cache of remote [machine]
names
and their IP addresses
-n (names) List local NetBIOS names.
-r (resolved) List names resolved by broadcast and via
WINS
-R (Reload) Purge and reloads the remote cache name
table
-S (Sessions) List sessions table with the destination
IP addresses
-s (sessions) List sessions table converting
destination IP
addresses to computer NETBIOS names.
-RR (ReleaseRefresh) Send Name Release packets to WINS and
then, starts Refresh
interval Redisplay selected statistics, pausing
interval seconds
between each display. Press Ctrl+C to
stop redisplaying
statistics.
NETSTAT.exe Display current TCP/IP network connections and protocol statistics. Syntax
NETSTAT [options] [-p protocol] [interval]
Key
-a Display All connections and listening ports.
-e Display Ethernet statistics. (may be combined with -s)
-n Display addresses and port numbers in Numerical form.
-r Display the Routing table.
-o Display the Owning process ID associated with each
connection.
-b Display the exe involved in creating each connection or
listening port.*
-v Verbose - use in conjunction with -b, to display the
sequence of
components involved for all executables.
-p protocol
Show only connections for the protocol specified;
may be any of: TCP, UDP, TCPv6 or UDPv6.
If used with the -s option then the following protocols
Windows Command Prompt www.nubielab.com Page 41
may also be specified: IP, IPv6, ICMP,or ICMPv6.
-s Display per-protocol statistics. By default, statistics
are
shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and
UDPv6;
(The v6 protocols are not available under 2k and NT4)
The -p option may be used to display just a subset of
these.
interval Redisplay statistics, pausing interval seconds
between
each display. (default=once only) Press CTRL+C
to stop.
* Where available this will display the sequence of components involved in creating the
connection or listening port. (Typically well-known executables which host multiple independent
components.) This option will display the executable name in [ ] at the bottom, with the
component it called on top, repeated until TCP/IP is reached. The -b option can be time-
consuming and will fail unless you have sufficient permissions.
NSLOOKUP (TCP/IP) Lookup IP addresses on a NameServer. Syntax
Lookup the ip address of MyHost:
NSLOOKUP [-option] MyHost
Lookup ip address of MyHost on MyNameServer:
NSLOOKUP [-option] MyHost MyNameServer
Enter "command mode":
NSLOOKUP
Command Mode options:
help or ? - print a list of Command Mode options
exit or ^C - exit "command mode"
set all - print options, current server and host
finger [USER] - finger the optional NAME at the current
default host
MyHost - print ip address of MyHost
MyHost MyNameServer - print ip address of MyHost on
MyNameServer
set [no]debug - print debugging info
set [no]d2 - print exhaustive debugging info
set domain=NAME - set default domain name to NAME
set root=NAME - set root server to NAME
root - set current default server to the root
server NAME - set default server to NAME, using current
default server
lserver NAME - set default server to NAME, using initial
server
set srchlist=N1[/N2/.../N6] - set domain to N1 and search list
to N1, N2,...
set retry=X - set number of retries to X
set timeout=X - set initial time-out interval to X seconds
set [no]defname - append domain name to each query
set [no]recurse - ask for recursive answer to query
set [no]search - use domain search list
set [no]vc - always use a virtual circuit
set class=X - set query class (for example, IN
(Internet), ANY)
set [no]msxfr - use MS fast zone transfer
set ixfrver=X - current version to use in IXFR transfer
request
set type=X - set query type
set querytype=X - set query type
(e.g. A, ANY, CNAME, MX, NS, PTR, SOA,
SRV)
ls [opt] DOMAIN [> FILE] - list addresses in DOMAIN
(and optionally output to FILE)
-d - list all records
-t TYPE - list records of the given Type (for example,
A, CNAME,
MX, NS, PTR, and so on)
-a - list Aliases and canonical names.
Windows Command Prompt www.nubielab.com Page 42
view FILE - sort an 'ls' output file and view it with pg
Example:
C:\> nslookup -querytype=TXT -timeout=10 porttest.dns-oarc.net
NTRIGHTS.exe (Resource Kit, 2000/2003) Edit user account Privileges. Syntax
NTRIGHTS +r Right -u UserOrGroup [-m \\Computer] [-e
Entry]
NTRIGHTS -r Right -u UserOrGroup [-m \\Computer] [-e
Entry]
Key:
+/-r Right Grant or revoke one of the rights listed
below.
-u UserOrGroup Who the rights are to be granted or revoked
to.
-m \\Computer The computer (machine) on which to perform
the operation.
The default is the local computer.
-e Entry Add a text string 'Entry' to the computer's
event log.
Below are the Privileges that can be granted or revoked, all are Case-Sensitive.
Logon Privileges: Log on as a batch job SeBatchLogonRight
Deny logon as a batch job SeDenyBatchLogonRight
Log on locally SeInteractiveLogonRight
Deny local logon SeDenyInteractiveLogonRight
Logon as a service SeServiceLogonRight
Deny logon as a service SeDenyServiceLogonRight
Access this Computer from the Network
SeNetworkLogonRight
Deny Access to this computer from the network
SeDenyNetworkLogonRight
Allow logon through Terminal Services
SeRemoteInteractiveLogonRight (Not supported on Win 2000)
Deny logon through Terminal Services
SeDenyRemoteInteractiveLogonRight (Not supported on Win 2000)
System Admin Privileges:
Generate security audits SeAuditPrivilege
Manage auditing and security log SeSecurityPrivilege
Backup files and directories SeBackupPrivilege
Add workstations to the domain SeMachineAccountPrivilege
Shut down the system SeShutdownPrivilege
Force shutdown from a remote system SeRemoteShutdownPrivilege
Create a pagefile SeCreatePagefilePrivilege
Increase quotas SeIncreaseQuotaPrivilege
Restore files and directories SeRestorePrivilege
Change the system time SeSystemTimePrivilege
Manage the files on a volume SeManageVolumePrivilege (Win
XP only)
Take ownership of files/objects SeTakeOwnershipPrivilege
Enable computer/user accounts
to be trusted for delegation
SeEnableDelegationPrivilege
Remove computer from docking station SeUndockPrivilege
Service Privileges: Create permanent shared objects SeCreatePermanentPrivilege
Create a token object SeCreateTokenPrivilege
Replace a process-level token SeAssignPrimaryTokenPrivilege
Impersonate a client after authentication
SeImpersonatePrivilege (Not supported on WinXP or earlier)
Increase scheduling priority
SeIncreaseBasePriorityPrivilege
Act as part of the operating system SeTcbPrivilege
Profile a single process
SeProfileSingleProcessPrivilege
Load and unload device drivers SeLoadDriverPrivilege
Lock pages in memory SeLockMemoryPrivilege
Create global objects SeCreateGlobalPrivilege (Not
supported on Windows XP or earlier)
Misc Privileges: Debug programs SeDebugPrivilege
Bypass traverse checking SeChangeNotifyPrivilege
Synch directory service data SeSyncAgentPrivilege
Edit firmware environment values SeSystemEnvironmentPrivilege
Profile system performance SeSystemProfilePrivilege
Obsolete and unused SeUnsolicitedInputPrivilege
(has no effect)
To run ntrights you need to be an administrator, to change privileges remotely (-m option) you
need to have administrator rights on the machine being changed.
To change permissions for a large number of users, add them to a domain workgroup and grant
the privileges to the group.
The group policy editor can be used to view these privileges in a GUI.
Windows Command Prompt www.nubielab.com Page 43
On a Windows 2008 Server (or Vista), allowing logon through Terminal Services
(SeRemoteInteractiveLogonRight) requires an extra step: Control Panel > System > 'Remote
Settings' > 'Select Users' button, and then add users/groups.
Examples: Allow all members of the local 'Users' group to logon locally
ntrights -u Users +r SeInteractiveLogonRight Allow all members of the 'Admin_RDP' group to logon remotely via RDP to "server64", also log
this security change in the event log:
ntrights -u MyDom\Admin_RDP +r SeRemoteInteractiveLogonRight -m \\server64 -e "Added RDP rights for Admin_RDP" Allow all members of the domain group 'Admin_General' to shutdown this computer.
ntrights -u MyDom\Admin_General +r SeShutdownPrivilege Allow the domain user 'JDoe' to shutdown the machine 'Server64'
ntrights -u MyDom\JDoe +r SeShutdownPrivilege -m \\Server64 Specifically deny local logon rights to Henry:
ntrights -u Henry +r SeDenyInteractiveLogonRight "What distinguishes the majority of men from the few is their inability to act according to their
beliefs." - Henry Miller
OPENFILES.exe Query or display open files, disconnect files opened by network users. Syntax
Openfiles.exe /query [/s Computer [/u Domain\User [/p
Password]]]
[/fo {TABLE|LIST|CSV}] [/nh] [/v]
Openfiles.exe /disconnect [/s Computer [/u Domain\User
[/p Password]]]
{[/id OpenFileID]|[/a UserName]|[/o OpenMode]} [/se
SessionName] [/op OpenFileName]
Key
/s The name or IP address of a remote computer. (Do not
use backslashes.) default=local computer.
/u Run the command with the account permissions of user.
Default=current logged on user.
/p The password of the user account specified with /u.
/fo The format to use for the query output. Valid values
are TABLE, LIST, and CSV. Default=TABLE.
/nh No column headers in the output. Valid only when /fo =
TABLE or CSV.
/id Disconnect the file opened with the specified numeric
OpenFileID on computer
Use openfiles.exe /query to learn the file ID.
The wildcard (*) can be used to disconnect all open
files on computer.
/a Disconnect all open files that were accessed by user
on computer.
The wildcard (*) can be used to disconnect all open
files on computer.
/o Disconnect all open files with the specified OpenMode
on the computer specified by the /s parameter.
The OpenMode parameter includes the Read/Write and
Read modes.
The wildcard (*) can be used to disconnect all open
files on computer.
/se Disconnect all open files that were created by the
specified session on computer.
Wildcards (*) may be used. (the /se option is not
available under Windows 7)
/op Disconnect the open file that was created with the
specified OpenFileName on computer
The wildcard (*) can be used to disconnect all open
files on computer.
/v Display verbose information in the output.
/? Help.
Administrator privileges are required to run the OPENFILES command. This can be used to
detect if the current user is an Admin OPENFILES > nul will set %ERRORLEVEL% = 1 if the
user is not an administrator - see this forum thread.
Running openfiles.exe from within powershell allows the output to be assigned to a variable.
Examples
PS C:\> openfiles /query PS C:\> openfiles /query /fo table /nh PS C:\> $file_list = openfiles /query /s Server64 /fo CSV /v /nh C:\> openfiles /query /fo list /v C:\> openfiles /query /s Server64 /u SS64Dom\FileAdmin /p password1
Windows Command Prompt www.nubielab.com Page 44
PS C:\> openfiles /disconnect /id 1 PS C:\> openfiles /disconnect /a mike C:\> openfiles /disconnect /o read/write C:\> openfiles /disconnect /op "c:\work\finance.xls" C:\> openfiles /disconnect /s Server64 /u SS64Dom\FileAdmin /id 5 C:\> openfiles /disconnect /s Server64 /u SS64Dom\FileAdmin /p password1 /id *
PATHPING Trace route and provide network latency and packet loss for each router and link in the path.
Combines the functionality of PING and TRACERT. Syntax
PATHPING [-n] [-h max_hops] [-g host_list] [-p period]
[-q num_queries] [-w timeout] [-i IPAddress] [-4 ] [-6
][TargetName]
Key
-g host_list - Loose source route along host-list.
-h max_hops - Maximum number of hops to search for target.
-i address - Use the specified source address.
-n - Do not resolve addresses to hostnames.
-p period - Wait period milliseconds between pings.
-q num_queries - Number of queries per hop.
-w timeout - Wait timeout milliseconds for each reply.
-P - Test for RSVP PATH connectivity.
-R - Test if each hop is RSVP aware.
-T - Test connectivity to each hop with Layer-2 priority
tags.
-4 - Force using IPv4.
-6 - Force using IPv6.
Pathping is invaluable for determining which routers or subnets may be having network
problems - it displays the degree of packet loss at any given router or link.
Pathping sends multiple Echo Request messages to each router between a source and destination
over a period of time and computes aggregate results based on the packets returned from each
router.
Pathping performs the equivalent of the tracert command by identifying which routers are on the
path.
To avoid network congestion and to minimize the effect of burst losses, pings should be sent at a
sufficiently slow pace (not too frequently.)
When -p is specified, pings are sent individually to each intermediate hop. When -w is specified,
multiple pings can be sent in parallel. It's therefore possible to choose a Timeout parameter that is
less than the wait Period * Number of hops.
Firewalls
Like tracert PathPing uses Internet Control Message Protocol (ICMP) over TCP/IP. Many
firewalls will block ICMP traffic by default. If an attacker is able to forge ICMP redirect packets,
he or she can alter the routing tables on the host and possibly subvert the security of the host by
causing traffic to flow via a path you didn't intend.
PERMS.exe (Windows 2000) Display a user’s ACL access permissions for a file. Output from PERMS may be misleading in
cases where a user has inherited permission through membership of a workgroup. Syntax
PERMS [account] [path] options
Key
account : username or [domain\|computer\]username
path : name of a file or folder in any legal format
including UNC names
Wildcards are permitted.
/i : interactively logged on to the computer
where the path resides.
(rather than being connected via the network)
/s : include subfolders
Access Description
R Read file/folder.
W Write file/folder.
X Execute file.
D Delete file or folder. May be inherited from the parent
folder
via 'Delete Subfolder and Files' permission.
P Change Permission.
O Take Ownership.
A General All
- No Access
Windows Command Prompt www.nubielab.com Page 45
* The specified user is the owner of the file or folder.
# A group the user is a member of owns the file or folder.
? Permisssions cannot be determined.
TypePerf.exe
Write performance data to the command window or to a log file.To stop Typeperf, press
CTRL+C. Syntax
typeperf counter [counter ...] [options]
typeperf -cf filename [options]
typeperf -q [object] [options]
typeperf -qx [object] [options]
Key
counter The Performance counters to monitor.
-f {CSV|TSV|BIN|SQL} Output file format. Default is CSV.
-cf filename File containing performance counters to
monitor, one per line.
-si [[hh:]mm:]ss Time between samples. Default is 1
second.
-o filename Path of output file or SQL database.
Default is STDOUT.
-q [object] List installed counters (no instances).
To list counters for one object,
include the object name, such as
Processor.
-qx [object] List installed counters with instances.
To list counters for one object,
include the object name, such as
Processor.
-sc samples Number of samples to collect. Default is
to sample until CTRL+C.
-config filename Settings file containing command
options.
-s computer_name Server to monitor if no server is
specified in the counter path.
-y Answer yes to all questions without
prompting.
-? Display context sensitive help.
Counter is the full name of a performance counter in the
format:"\\Computer\Object(Instance)\Counter"
e.g. "\\Server1\Processor(0)\% User Time".
Examples Display % Processor time until interrupted:
C:\> typeperf "\Processor(_Total)\% Processor Time"
Gather 600 samples of % Processor time on the local computer (this will take 10 minutes):
C:\> typeperf "\processor(_Total)\% Processor Time" -O C:\SS64demo1.csv -SC 600
Gather samples of all the counters listed in counters.txt :
C:\> typeperf -cf counters.txt -si 5 -sc 50 -o C:\SS64demo2.csv
PING Test a network connection - if successful, ping returns the ip address. Syntax
PING [options] destination_host
Options
-w timeout Timeout in milliseconds to wait for each
reply.
-i TTL Time To Live.
-v TOS Type Of Service.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-t Ping the destination host until interrupted.
-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.
A successful PING does NOT always return an %errorlevel% == 0
Therefore to reliably detect a successful ping - pipe the output into FIND and look for the text
"TTL"
Note that "Reply" in the output of PING does not always indicate a positive response. You may
receive a message from a router such as: Reply from 192.168.1.254: Destination Net
Unreachable.
Four steps to test an IP connection with ping:
Windows Command Prompt www.nubielab.com Page 46
1) Ping the loopback address to verify that TCP/IP is installed and configured correctly on the
local computer.
PING 127.0.0.1
2) Ping the IP address of the local computer to verify that it was added to the network correctly.
PING IP_address_of_local_host
3) Ping the IP address of the default gateway to verify that the default gateway is functioning and
that you can communicate with a local host on the local network.
PING IP_address_of_default_gateway
4) Ping the IP address of a remote host to verify that you can communicate through a router.
PING IP_address_of_remote_host
Examples PING -n 1 -w 7500 Server_06
PING -w 7500 MyHost |find "TTL=" && ECHO MyHost found
PING -w 7500 MyHost |find "TTL=" || ECHO MyHost not found
PING -n 5 -w 7500 www.microsoft.com
PING -n 5 -w 7500 microsoft.com
Script to monitor your connection to a website (example.com) every 15 seconds: @Echo off
Echo Logging ping responses, press CTRL-C to stop
:start
Ping -n 1 example.com | find "TTL=" >>c:\pingtest.txt
Echo .
Ping -n 16 127.0.0.1>nul
goto start
The script above can be used to test an Internet connection, just replace example.com with your
ISP's Default Gateway IP address. This represents the first physical device on the ISP's side of
your connection. You can find the Default Gateway on your router status screen.
Note: some ISP’s or network admins may not appreciate you performing frequent or continual
pings to their server, try not to overdo it!
PING is named after the sound that a sonar makes.
Ping times below 10 milliseconds often have low accuracy. A time of 10 milliseconds is roughly
equal to a distance of 930 Miles, travelling a straight line route at the speed of light.
REG.exe Read, Set or Delete registry keys and values, save and restore from a .REG file.
Syntax:
REG QUERY [ROOT\]RegKey /v ValueName [/s]
REG QUERY [ROOT\]RegKey /ve --This returns the (default)
value
REG ADD [ROOT\]RegKey /v ValueName [/t DataType] [/S
Separator] [/d Data] [/f]
REG ADD [ROOT\]RegKey /ve [/d Data] [/f] -- Set the
(default) value
REG DELETE [ROOT\]RegKey /v ValueName [/f]
REG DELETE [ROOT\]RegKey /ve [/f] -- Remove the (default)
value
REG DELETE [ROOT\]RegKey /va [/f] -- Delete all values under
this key
REG COPY [\\SourceMachine\][ROOT\]RegKey
[\\DestMachine\][ROOT\]RegKey
REG EXPORT [ROOT\]RegKey FileName.reg
REG IMPORT FileName.reg
REG SAVE [ROOT\]RegKey FileName.hiv
REG RESTORE \\MachineName\[ROOT]\KeyName FileName.hiv
REG LOAD FileName KeyName
REG UNLOAD KeyName
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/v ValueName]
[Output] [/s]
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/ve] [Output] [/s]
Key:
ROOT :
HKLM = HKey_Local_machine (default)
HKCU = HKey_current_user
HKU = HKey_users
HKCR = HKey_classes_root
ValueName : The value, under the selected RegKey, to edit.
(default is all keys and values)
/d Data : The actual data to store as a "String", integer
etc
Windows Command Prompt www.nubielab.com Page 47
/f : Force an update without prompting "Value exists,
overwrite Y/N"
\\Machine : Name of remote machine - omitting defaults to
current machine.
Only HKLM and HKU are available on remote
machines.
FileName : The filename to save or restore a registry hive.
KeyName : A key name to load a hive file into. (Creating a
new key)
/S : Query all subkeys and values.
/S Separator : Character to use as the separator in
REG_MULTI_SZ values
the default is "\0"
/t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ |
REG_MULTI_SZ
Output : /od (only differences) /os (only matches) /oa
(all) /on (no output)
Notes: Any of the above commands can be run against a remote machine by adding \\MachineName to
the command line, assuming the Remote Registry Service is running.
Registry data stored under HKCU will be visible and writable by the currently logged in user.
Registry data stored under HKLM will be visible to all users and writable by administrators.
To include a quote mark (") in the data, prefix it with the escape character (\) e.g. "Here is \" a
quote"
Enclose ValueNames that contain the \ character in single quotes.
REG RESTORE has a tendency not to work, possibly due to firewall issues, Export and Import
are much more reliable.
Examples REG QUERY HKCU\Console\
REG QUERY HKCU\Console /v ScreenBufferSize
REG ADD HKCU\Software\SS64 /v Sample /d "some test data"
REG QUERY HKCU\Software\SS64 /v Sample
REG ADD HKLM\Software\DiLithium /v WarpSpeed /t REG_BINARY /d
ffffffff
REG QUERY HKLM\Software\DiLithium /v WarpSpeed
REG COPY \\Wks580\HKCU\Software\SS64 HKCU\Software\SS64
REG COPY HKCU\Software\SS64 HKCU\Software\SS64Copy
REG EXPORT HKCU\Software\SS64 C:\MyReg.REG
REG IMPORT C:\MyReg.REG
REG SAVE HKCU\Software\SS64 C:\MyRegHive.hiv
REG RESTORE \\Wks580\HKCU\Software\SS64 C:\MyRegHive.hiv
Run a script at first logon (Run Once) to do this we edit the Default User profile by temporarily
loading it as ZZZ: REG LOAD HKU\ZZZ "C:\Documents and Settings\Default
User\NTUSER.DAT"
REG ADD
HKU\ZZZ\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce /v
newUserProfile /t REG_EXPAND_SZ /d "D:\setup.cmd" /f
REG UNLOAD HKU\ZZZ
REGEDIT Import, export or delete registry settings from a text (.REG) file Syntax
Export the Registry (all HKLM plus current user)
REGEDIT /E pathname
Export part of the Registry
REGEDIT /E pathname "RegPath"
Import a reg script
REGEDIT pathname
Silent import
REGEDIT /S pathname
Start the regedit GUI
REGEDIT
Open multiple copies of GUI (XP and 2003 only)
REGEDIT -m
Key
/E : Export
/S : Silent Import
How to add keys and values from the registry:
Create a text file like this:
Windows Command Prompt www.nubielab.com Page 48
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SomeKey]
"SomeStringValue"="Hello"
When double clicking this .reg file the key and value will be added.
Alternatively run REGEDIT MYKEY.REG from the command line.
How to delete keys and values from the registry:
Create a reg file like this, notice the hyphen inside the first bracket Windows Registry Editor Version 5.00
[-HKEY_CURRENT_USER\SomeKey]
When double clicking this .reg file the key "SomeKey" will be deleted along with all string,
binary or Dword values in that key.
If you want to just delete values, leaving the key in place, set the value you want to delete = to a
hyphen
e.g. Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SomeKey]
"SomeStringValue"=-
Again double clicking this .reg file will delete the values specified, or you can use REGEDIT /s
MyDeleteScript.REG
Compare the Registry of two machines Windiff is your friend, this simple GUI utility from the resource kit will list all the differences.
Comments Within a registry file, comments can be preceded by "; "
e.g.
;
; Turn the NUMLOCK on at login
;
[HKEY_CURRENT_USER\Control Panel\Keyboard]
"InitialKeyboardIndicators"="2"
Under Windows NT 4 all registry scripts start with: REGEDIT4
(This version string will also work in XP and later versions of Windows.)
REGSVR32
Register or unregister a DLL. Syntax
REGSVR32 [/U] [/S] [/C] [/I:[Command_Line]] DLL_Name
REGSVR32 [/U] [/S] [/C] /N /I:[Command_Line] DLL_Name
Key
/u Unregister Server.
/s Silent - no dialogue boxes.
/c Console output.
/n Don't call DllRegisterServer
/i Call DllInstall (or DllUninstall if /u is
specified)
Command_Line An optional command line for DllInstall
Examples Unregister (disable) XP Zip folders
REGSVR32 /u C:\Windows\System32\zipfldr.dll
Unregister (Disable) CAB file viewer:
REGSVR32 /u C:\Windows\System32\cabview.dll
Register (enable) XP Zip folders
REGSVR32 zipfldr.dll
Register (enable) CAB file viewer:
REGSVR32 cabview.dll
Register Windows Update DLLs (for those times when XP repair breaks Windows Update)
regsvr32 /s wuapi.dll
regsvr32 /s wuaueng1.dll
regsvr32 /s wuaueng.dll
regsvr32 /s wucltui.dll
regsvr32 /s wups2.dll
regsvr32 /s wups.dll
regsvr32 /s wuweb.dll
Register DAO 3.6 (Data Access Objects):
REGSVR32 "C:\Program Files\Common Files\Microsoft Shared\DAO\DAO360.DLL"
REGINI (Resource kit) Change Registry Permissions. Syntax
REGINI [-m \\machinename | -h hivefile hiveroot | -w
Win95Directory]
[-i n] [-o outputWidth]
[-b] textFiles...
Key
-m A remote computer.
-h The local hive to manipulate.
Windows Command Prompt www.nubielab.com Page 49
-w Path to Windows 95 system.dat / user.dat files
-i n The display indentation multiple. Default is 4
-o outputWidth
How wide the output is to be. By default the
outputWidth is set to the width of the console window
if standard
output has not been redirected to a file. In the
latter case, an
outputWidth of 240 is used.
-b Make REGINI backward compatible with older versions of
REGINI that
did not strictly enforce line continuations and quoted
strings
Specifically, REG_BINARY, REG_RESOURCE_LIST and
REG_RESOURCE_REQUIREMENTS_LIST data types did not need
line
continuations after the first number that gave the
size of the data.
It just kept looking on following lines until it
found enough data
values to equal the data length or hit invalid input.
Quoted
strings were only allowed in REG_MULTI_SZ. They
could not be
specified around key or value names, or around values
for REG_SZ or
REG_EXPAND_SZ Finally, the old REGINI did not
support the semicolon
as an end of line comment character.
textFiles One or more ANSI or Unicode text files with
registry data.
The easiest way to understand the format of the input textFile is to use the REGDMP command
with no arguments to dump the current contents of
your NT Registry to standard out. Redirect standard out to a file and this file is acceptable as
input to REGINI
Some general rules are:
Semicolon character is an end-of-line comment character, provided it is the first non-blank
character on a line
Backslash character is a line continuation character. All characters from the backslash up to but
not including the first non-blank character of the next line are ignored. If there is more than one
space before the line continuation character, it is replaced by a single space.
Indentation is used to indicate the tree structure of registry keys The REGDMP program uses
indentation in multiples of 4. You may use hard tab characters for indentation, but embedded
hard tab characters are converted to a single space regardless of their position
Values should come before child keys, as they are associated with the previous key at or above
the value's indentation level.
For key names, leading and trailing space characters are ignored and not included in the key
name, unless the key name is surrounded by quotes. Imbedded spaces are part of a key name.
Key names can be followed by an Access Control List (ACL) which is a series of decimal
numbers, separated by spaces, bracketed by a square brackets (e.g. [8 4 17]). The valid numbers
and their meanings are: 1 - Administrators Full Access
2 - Administrators Read Access
3 - Administrators Read and Write Access
4 - Administrators Read, Write and Delete Access
5 - Creator Full Access
6 - Creator Read and Write Access
7 - World Full Access
8 - World Read Access
9 - World Read and Write Access
10 - World Read, Write and Delete Access
11 - Power Users Full Access
12 - Power Users Read and Write Access
13 - Power Users Read, Write and Delete Access
14 - System Operators Full Access
15 - System Operators Read and Write Access
16 - System Operators Read, Write and Delete
Access
17 - System Full Access
18 - System Read and Write Access
19 - System Read Access
20 - Administrators Read, Write and Execute Access
21 - Interactive User Full Access
22 - Interactive User Read and Write Access
23 - Interactive User Read, Write and Delete
Access
If there is an equal sign on the same line as a left square bracket then the equal sign takes
precedence, and the line is treated as a registry value. If the text between the square brackets is
the string DELETE with no spaces, then REGINI will delete the key and any values and keys
under it.
Windows Command Prompt www.nubielab.com Page 50
For registry values, the syntax is:
value Name = type data
Leading spaces, spaces on either side of the equal sign and spaces between the type keyword and
data are ignored, unless the value name
is surrounded by quotes. If the text to the right of the equal sign is the string DELETE, then
REGINI will delete the value.
The value name may be left off or be specified by an at-sign character which is the same thing,
namely the empty value name. So the following two lines are identical:
= type data
@ = type data
This syntax means that you can't create a value with leading or trailing spaces, an equal sign or
an at-sign in the value name, unless you put the name in quotes. Valid value types and format of data that follows are:
REG_SZ text
REG_EXPAND_SZ text
REG_MULTI_SZ "string1" "str""ing2" ...
REG_DATE mm/dd/yyyy HH:MM DayOfWeek
REG_DWORD numberDWORD
REG_BINARY numberOfBytes numberDWORD(s)...
REG_NONE (same format as REG_BINARY)
REG_RESOURCE_LIST (same format as REG_BINARY)
REG_RESOURCE_REQUIREMENTS (same format as
REG_BINARY)
REG_RESOURCE_REQUIREMENTS_LIST (same format as
REG_BINARY)
REG_FULL_RESOURCE_DESCRIPTOR (same format as
REG_BINARY)
REG_QWORD numberQWORD
REG_MULTISZ_FILE fileName
REG_BINARYFILE fileName
If no value type is specified, default is REG_SZ
For REG_SZ and REG_EXPAND_SZ, if you want leading or trailing spaces in the value text,
surround the text with quotes. The value text
can contain any number of imbedded quotes, and REGINI will ignore them, as it only looks at
the first and last character for quote characters.
For REG_MULTI_SZ, each component string is surrounded by quotes. If you want an imbedded
quote character, then double quote it, as in string2 above.
For REG_BINARY, the value data consists of one or more numbers The default base for
numbers is decimal. Hexidecimal may be specified by using 0x prefix. The first number is the
number of data bytes, excluding the first number. After the first number must come enough
numbers to fill the value. Each number represents one DWORD or 4 bytes. So if the first number
was 0x5 you would need two more numbers after that to fill the 5 bytes. The high order 3 bytes
of the second DWORD would be ignored.
Whenever specifying a registry path, either on the command line or in an input file, the
following prefix strings can be used: HKEY_LOCAL_MACHINE
HKEY_USERS
HKEY_CURRENT_USER
USER:
Each of these strings can stand alone as the key name or be
followed
a backslash and a subkey path.
There are several versions of regini with different syntax - the resource kit includes a word
document with help and examples.
REN Rename a file or files. REN [drive:][path]old_filename new_filename
RENAME is a synonym for REN
You cannot specify a different drive or path for `new_filename` - use the MOVE command
instead.
Both the source and/or destination may include wildcards. e.g.
REN *.txt *.xyz
REN c:\MyFile.txt *.xyz
REN c:\MyFile.txt ????.xyz
"We may dig in our heels and dare life never to change, but, all the same, it changes under our
feet like sand under the feet of a sea gazer as the tide runs out. Life is forever undermining us.
Life is forever washing away our castles, reminding us that they were, after all, only sand and
sea water." - Erica Jong (Parachutes and Kisses)
REPLACE Replace or update one file with another Syntax
Windows Command Prompt www.nubielab.com Page 51
REPLACE Source_PathName Destination_path [/A] [/P] [/R]
[/W]
REPLACE Source_PathName Destination_path [/P] [/R] [/S]
[/W] [/U]
Key
path : The folder where files are to be replaced.
/A : Add any missing files.
/P : Prompt for confirmation (each file)
/R : Replace even Read-only files
/S : Include all subfolders of the destination.
/W : Wait for you to insert a floppy disk.
/U : Replace (update) only files that are older than the
source.
Limitations:
When replacing in all subdirectories (/S ) you cannot ADD files (/A) or restrict to replacing older
files (/U)
RD
Delete folder(s) Syntax
RD pathname
RD /S pathname
RD /S /Q pathname
Key
/S : Delete all files and subfolders
in addition to the folder itself.
Use this to remove an entire folder tree.
/Q : Quiet - do not display YN confirmation
Place any long pathnames in double quotes.
RD does not support wildcards but you can remove several folders in one command by listing
the pathname to each.
e.g.
RD c:\docs\Jan c:\docs\Feb "c:\My Documents\Mar"
RMDIR is a synonym for RD
ROUTE.exe Manipulate network routing tables. Route packets of network traffic from one subnet to another
by modifying the route table. Syntax
Display route details:
ROUTE [-f] PRINT [destination_host] [MASK
subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Add a route:
ROUTE [-f] [-p] ADD [destination_host] [MASK
subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Change a route:
ROUTE [-f] CHANGE [destination_host] [MASK
subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Delete a route:
ROUTE [-f] DELETE [destination_host] [MASK
subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
key
-f Clear (flush) the routing tables of all gateway
entries. If this is
used in conjunction with one of the commands, the
tables are
cleared prior to running the command.
destination_host
The address (or set of addresses) that you want
to reach.
-p Create a persistent route - survives system
reboots.
(not supported in Windows 95)
Windows Command Prompt www.nubielab.com Page 52
subnet_mask_value
The subnet mask value for this route entry.
This defines how many addresses are there.
If not specified, it defaults to 255.255.255.255.
gateway The gateway.
interface The interface number (1,2,...) for the specified
route.
If the option `IF interface_no` is not given,
ROUTE will try
to find the best interface available.
metric The metric, ie. cost for the destination.
Note that routes added to the table are not made persistent unless the -p switch is specified. Non-
persistent routes only last until the computer is rebooted.
Symbolic names used for Destination_Host are looked up in the network database file
NETWORKS.
The symbolic names for gateway are looked up in the host name database file HOSTS.
If the command is PRINT or DELETE. Destination or gateway can be a wildcard ('*'), or the
gateway argument may be omitted.
An IP address mask of 0.0.0.0 means everything. (rather like the *.* wildcard). In other words it
says: When matching this pattern, don't worry about matching any of the bits - everything
matches.
If Destination_Host contains a * or ?, it is treated as a shell pattern, and only matching
destination routes are printed. The '*' matches any string, and '?' matches any one char.
Examples:
157.*.1
157.*
127.*
*224*
SYSTEMINFO
List system configuration Syntax
SYSTEMINFO [/S system [/U username [/P [password]]] ]
[/FO format] [/NH]
Key:
/S system Remote system to connect to.
/U [domain\]user User context under which to execute.
/P [password] Password for the given user (will prompt
if omitted)
/FO format Output format: TABLE, LIST or CSV
/NH No "Column Header" in the Table/CSV
output
The output includes OS configuration, security info, product ID, RAM, disk space, and network
cards.
Examples
SYSTEMINFO
SYSTEMINFO |find "Total Physical Memory:"
SYSTEMINFO /S wkstn6324
SYSTEMINFO /S wkstn6325 /FO CSV /NH >>pcaudit.csv
TASKLIST
TaskList displays all running applications and services with their Process ID (PID) This can be
run on either a local or a remote computer. Syntax
tasklist options
Options:
/s computer Name or IP address of a remote computer
don't use backslashes. Default = local computer.
/u domain\user [/p password]]
Run under a different account
/svc List information for each process without
truncation.
Valid when /fo=TABLE. Cannot be used with /m or
/v
/m [ModuleName]
Show the processes that include the given
module.
/v Verbose task information
/fo {TABLE|LIST|CSV}]
Output format, the default is TABLE.
/nh No Headers in the output (does not apply to LIST
output)
/fi FilterName [/fi FilterName2 [ ... ]]
Apply one of the Filters below:
Windows Command Prompt www.nubielab.com Page 53
Imagename eq, ne String
PID eq, ne, gt, lt, ge, le Positive
integer.
Session eq, ne, gt, lt, ge, le Any valid
session number.
SessionName eq, ne String
Status eq, ne RUNNING |
NOT RESPONDING
CPUTime eq, ne, gt, lt, ge, le Time
hh:mm:ss
MemUsage eq, ne, gt, lt, ge, le Any valid
integer.
Username eq, ne User name
([Domain\]User).
Services eq, ne String
Windowtitle eq, ne String
Modules eq, ne String
Examples: tasklist /svc
tasklist /v /fi "STATUS eq running"
tasklist /v /fi "username eq ORACLE_SERVICE_ACCOUNT"
WMIC can also list running processes and parameters: WMIC /OUTPUT:C:\ProcList.txt PROCESS get
Caption,Commandline,Processid
TASKLIST
End one or more processes (by process id or image name). Syntax
TASKKILL [/S system [/U username [/P [password]]]]
{ [/FI filter] [/PID processid | /IM imagename] } [/F]
[/T]
Options
/S system The remote system to connect to.
/U [domain\]user The user context under which
the command should execute.
/P [password] The password. Prompts for input if
omitted.
/F Forcefully terminate the process(es).
/FI filter Display a set of tasks that match a
given criteria specified by the
filter.
/PID process id The PID of the process to be
terminated.
/IM image name The image name of the process to be
terminated.
Wildcard '*' can be used to specify
all image names.
/T Tree kill: terminates the specified
process
and any child processes which were
started by it.
Filters Apply one of the Filters below:
Imagename eq, ne String
PID eq, ne, gt, lt, ge, le Positive
integer.
Session eq, ne, gt, lt, ge, le Any valid
session number.
Status eq, ne RUNNING | NOT
RESPONDING
CPUTime eq, ne, gt, lt, ge, le Time hh:mm:ss
MemUsage eq, ne, gt, lt, ge, le Any valid
integer.
Username eq, ne User name
([Domain\]User).
Services eq, ne String The
service name
Windowtitle eq, ne String
Modules eq, ne String The DLL
name
Examples: Examples:
TASKKILL /S system /F /IM notepad.exe /T
TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
TASKKILL /F /IM notepad.exe /IM mspaint.exe
TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"
TASKKILL /F /FI "USERNAME eq NT AUTHORITY\SYSTEM" /IM
notepad.exe
Windows Command Prompt www.nubielab.com Page 54
TASKKILL /S system /U domain\username /FI "USERNAME ne NT*"
/IM *
TASKKILL /S system /U username /P password /FI "IMAGENAME eq
note*"
TRACERT
Trace Route - Find the IP address of any remote host. TRACERT is useful for troubleshooting
large networks where several paths can be taken to arrive at the same point, or where many
intermediate systems (routers or bridges) are involved. Syntax
TRACERT [options] target_name
Key
target_name The HTTP or UNC name of the host
Options:
-d Do not resolve addresses to hostnames.
(avoids performing a DNS lookup)
-h max_hops Maximum number of hops to search for
target.(default=30)
-j host-list Trace route along given host-list.
up to 9 hosts in dotted decimal notation,
separated by spaces.
-w timeout Wait timeout milliseconds for each reply.
The functionality of TRACERT is the same under all versions of windows but the output is
cosmetically improved under XP.
Tracert uses the IP TTL field and ICMP error messages to determine the route from one host to
another through a network.
Care must be taken with tracert as it shows the optimal route, not necessarily the actual route. To
be accurate, it is possible to ping from a UNIX machine back to the PC using the -R option to
record the route taken - but only if the particular network devices support it.
This diagnostic tool determines the path taken to a destination by sending ICMP Echo Request
messages with varying Time to Live (TTL) values to the destination.
TTL (Time to Live) calculation TTL is effectively a count of the (maximum) number of links to the destination host. Each router
along the path decrements the TTL in an IP packet by at least 1 before forwarding it.
When the TTL on a packet reaches 0, the router is expected to return an ICMP Time Exceeded
message to the source computer.
Tracert determines the path by sending the first Echo Request message with a TTL of 1 and
incrementing the TTL by 1 on each subsequent transmission until either the target host responds
or the maximum number of hops is reached.
This process relys on intermediate routers to return ICMP Time Exceeded messages. However,
some routers do not return Time Exceeded messages for packets with expired TTL values and are
invisible to the tracert command. In this case, a row of asterisks (*) is displayed for that hop.
Firewalls
Many firewalls will block ICMP traffic by default. If an attacker is able to forge ICMP redirect
packets, he or she can alter the routing tables on the host and possibly subvert the security of the
host by causing traffic to flow via a path you didn't intend.
Examples TRACERT www.doubleclick.net
TRACERT 123.45.67.89
TRACERT local_server
XCACLS.exe (Resource Kit)
Display or modify Access Control Lists (ACLs) for files and folders. Syntax
XCACLS filename [options]
XCACLS filename
Key
If no options are specified XCACLS will display the ACLs for
the file(s)
options can be any combination of:
/T Traverse all subfolders and change all matching
files found.
/E Edit ACL instead of replacing it.
/x Edit ACL instead of replacing it; affect only ACEs
that this user already owns*
/R user Revoke all access rights from the given user.
/D user Deny specified user access, this will over-ride
all other permissions the user has.
/C Continue on access denied errors.
/Y Replace user's rights without verify
/P user:permision[;FolderSpec]
Replace user's rights. see /G option below
Windows Command Prompt www.nubielab.com Page 55
/G user:permision[;FolderSpec]
Grant specified user access rights, permision can be:
r Read
c Change (write)
f Full control
p Change Permissions (Special access)
o Take Ownership (Special access)
x EXecute (Special access)
e REad (Special access)
w Write (Special access)
d Delete (Special access)
t Used only by FolderSpec. see below
* Option only valid in Windows 2003
FolderSpec is a permission applied to a folder. If FolderSpec is not specified then permission
will apply to both files and folders.
This allows you to set different permissions that will apply (through inheritance) when new files
are added to the folder.
FolderSpec = ;T@ where @ is one of the rights above, when this is specified new files will
inherit FolderSpec instead of permission. At least one folder access right must follow the T For
example ;TF will apply full control (but ;FT is not valid)
Wildcards can be used to specify more that one file in a command. You can specify more than
one user in a command. You can combine access rights.
Although taking ownership is listed as an option it does not work, use SUBINACL for this.
Inheritance Errors "Permissions incorrectly ordered" - the quickest way to resolve or avoid these errors is to use the
newer iCACLS command instead of XCACLS.
Inherited folder permissions are displayed as: OI - Object inherit - This folder and files. (no inheritance
to subfolders)
CI - Container inherit - This folder and subfolders.
IO - Inherit only - The ACE does not apply to the current
file/directory
These can be combined as folllows:
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
(OI) (IO) Files only.
So BUILTIN\Administrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F'
(Fullcontrol)
similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)
When xcacls is applied to the current folder only there is no inheritance and so no output.
Versions: NTFS standards have changed with different versions of Windows and XCACLS has been
updated to suit, early versions of Xcacls may give unpredictable results against an NTFS v5
partition.
xcacls.vbs is described in Q825751 and can be downloaded here - xcacls.vbs is an unsupported
utility that addresses a limitation with the original xcacls.exe, specifically the inability to append
permissions to a folder whose child objects have the inheritance flag set. The .vbs version does
not suppport unc paths and is very slow to update multiple ACLs.
Examples:
:: Allow guests the right to read and execute in MyFolder
XCACLS MyFolder /E /G guests:rx
:: Allow guests the Full Control permission in MyFolder and all subfolders
XCACLS MyFolder /T /E /G guests:f
:: Grant guests only read access to all files in and below MyFolder,
:: new folders created will be Read Access only, new files will not inherit any rights.
XCACLS MyFolder /T /P guests:R;Tr
:: Grant guests only execute access to all files in and below MyFolder
XCACLS MyFolder /T /P guests:x
XCOPY Copy files and/or directory trees to another folder. XCOPY is similar to the COPY command
except that it has additional switches to specify both the source and destination in detail.
XCOPY is particularly useful when copying files from CDROM to a hard drive, as it will
automatically remove the read-only attribute. Syntax
XCOPY source [destination] [options]
Key
source : Pathname for the file(s) to be copied.
destination : Pathname for the new file(s).
[options] can be any combination of the following:
Source Options
Windows Command Prompt www.nubielab.com Page 56
/A Copy files with the archive attribute set
(default=Y)
/M Copy files with the archive attribute set and
turn off the archive attribute, use this option
when making regular Backups (default=Y)
/H Copy hidden and system files and folders
(default=N)
/D:mm-dd-yyyy
Copy files that have changed since mm-dd-yyyy.
(files changed on or after the specified date)
If no date is given, the default is 1 day ago
(files changed on or after 00:01 yesterday.)
/U Copy only files that already exist in
destination.
/S Copy folders and subfolders
/E Copy folders and subfolders, including Empty
folders.
May be used to modify /T.
/EXCLUDE:file1[+file2][+file3]...
(Windows 2000 only) The files can each contain
one
or more full or partial pathnames to be excluded.
When any of these match any part of the absolute
path
of a SOURCE file, then that file will be
excluded.
For example, specifying a string like \obj\ or
.obj will exclude
all files underneath the directory obj or all
files with the
.obj extension respectively.
Copy Options
/W Prompt you to press a key before starting to
copy.
/P Prompt before creating each file.
/Y (Windows 2000 only) Suppress prompt to confirm
overwriting a file.
may be preset in the COPYCMD env variable.
/-Y (Windows 2000 only) Prompt to confirm
overwriting a file.
/V Verify that the new files were written
correctly.
/C Continue copying even if an error occurs.
/I If in doubt always assume the destination is a
folder
e.g. when the destination does not exist.
/Z Copy files in restartable mode. If the copy is
interrupted part
way through, it will restart if possible. (use
on slow networks)
/Q Do not display file names while copying.
/F Display full source and destination file names
while copying.
/L List only - Display files that would be copied.
Destination Options
/R Overwrite read-only files.
/T Create folder structure, but do not copy files.
Do not
include empty folders or subfolders.
/T /E will include empty folders and subfolders.
/K Copy attributes. XCOPY will otherwise reset
read-only attributes.
/N If at all possible, use only a short filename
(8.3) when creating
a destination file. This may be nececcary when
copying between disks
that are formatted differently e.g NTFS and
VFAT, or when archiving
data to an ISO9660 CDROM.
Windows Command Prompt www.nubielab.com Page 57
/O (Windows 2000 only) copy file Ownership and ACL
information.
/X Copy file audit settings (implies /O).
XCOPY will accept UNC pathnames
Examples:
To copy a file:
XCOPY C:\utils\MyFile D:\Backup\CopyFile
To copy a folder:
XCOPY C:\utils D:\Backup\utils /i
To copy a folder including all subfolders.
XCOPY C:\utils\* D:\Backup\utils /s /i
The /i defines the destination as a folder.
Notes
In many cases the functionality of XCOPY is superseded by ROBOCOPY.
To force the overwriting of destination files under both NT4 and Windows2000 use the
COPYCMD environment variable:
SET COPYCMD=/Y
This will turn off the prompt in Win2000 and will be ignored by NT4 (which overwrites by
default).
When comparing Dates/Times the granularity (the finest increment of the timestamp) is 2
seconds for a FAT volume and 0.1 microsecond for an NTFS volume.
The WinXP version of XCOPY will accept wildcards for the source e.g. *.txt
It is also more forgiving with trailing backslashes
Syntax
Parameters A parameter (or argument) is any value passed into a batch script:
C:> MyScript.cmd January 1234 "Some value" Parameters may also be passed to a subroutine with CALL:
CALL :my_sub 2468 You can get the value of any parameter using a % followed by it's numerical position on the
command line. The first item passed is always %1 the second item is always %2 and so on
%* in a batch script refers to all the arguments (e.g. %1 %2 %3 %4 %5 ...%255)
Filename Parameter Extensions
When a parameter is used to supply a filename then the following extended syntax can be
applied:
we are using the variable %1 (but this works for any parameter)
%~f1 - expands %1 to a Fully qualified path name - C:\utils\MyFile.txt
%~d1 - expands %1 to a Drive letter only - C:
%~p1 - expands %1 to a Path only - \utils\
%~n1 - expands %1 to a file Name, or if only a path is present (with no trailing backslash\) - the
last folder in that path
%~x1 - expands %1 to a file eXtension only - .txt
%~s1 - changes the meaning of f, n and x to reference the Short name (see note below)
%~1 - expand %1 removing any surrounding quotes (")
%~a1 - display the file attributes of %1
%~t1 - display the date/time of %1
Windows Command Prompt www.nubielab.com Page 58
%~z1 - display the file size of %1
%~$PATH:1 - search the PATH environment variable and expand %1 to the fully qualified
name of the first match found.
The modifiers above can be combined:
%~dp1 - expands %1 to a drive letter and path only
%~nx2 - expands %2 to a file name and extension only
When writing batch scripts it's a good idea to store parameter values in a variable using the SET
command, the rest of the script can then refer to the easy-to-read name SET _LogFile=%~dp1
This will also make life easier if you later need to change around the order of the parameters.
Note on short file/folder names: There is a bug involving the ~s option - the displayed output may be wrong if the current
directory name is not the same as the 8.3 version of the directory.
A workaround is to run command.com /c rem , which will change the current directory to 8.3
e.g. if the current directory is C:\Program Files\ you will see the bug
if the current directory is C:\progra~1\ it will work fine (but then you wont see the long name)
more here
FOR command parameters The FOR command creates parameters which are identified with a letter rather than a number.
These are easily confused with the parameter modifier letters described above.
Therefore when using FOR it's best to avoid the letters (a, d, f, n, p, s, t, x, z), apart from making
code easier to follow, this can avoid problems when running under NT 4 and Windows 2000:
%0 - the Batch Script itself
You can get the pathname of the .CMD script itself with %0
If the script is stored on a network share, it may be accessed directly from the UNC share or via a
mapped drive.
You cannot set the current directory to a UNC path but you can refer to other files in the same
folder as the batch script by using this syntax: CALL %0\..\SecondBatch.cmd
This can even be used in a subroutine, Echo %0 will give the call label but, echo "%~nx0" will
give you the filename of the batch script.
When the %0 variable is expanded in Windows XP, the result is enclosed in quotation marks.
Examples: Pass parameters from one batch to another: MyBatch.cmd SMITH 100
Or as part of a CALL : CALL MyBatch.cmd SMITH 100
Passing values from one part of a script to another
Using CALL to jump to a subroutine
CALL :s_staff SMITH 100
Calling a subroutine from a FOR command
FOR /F %%G IN ('DIR /b *.*') DO call :s_subroutine %%G
Windows Environment Variables
Environment variables are mainly used within batch files, they can be created, modified and
deleted using the SET command.
Variables can be displayed using either SET or ECHO.
Variables have a percent sign on both sides: %ThisIsAVariable%
The variable name can include spaces, punctuation and mixed case: %_Another Ex.ample%
This is unlike Parameter Variables which only have one % sign and are always one character
long: %A
Standard (built-in) Environment Variables
Variable Default value: Windows XP
Default value: Windows 7/2008
%ALLUSERSPROFILE% C:\Documents and Settings\All Users
C:\ProgramData
%APPDATA% C:\Documents and Settings\{username}\Application Data
C:\Users\{username}\AppData\Roaming
%CommonProgramFiles% C:\Program Files\Common Files C:\Program Files\Common Files
%COMMONPROGRAMFILES(x86)% C:\Program Files (x86)\Common Files
C:\Program Files (x86)\Common Files
%COMPUTERNAME% {computername} {computername}
%COMSPEC% C:\Windows\System32\cmd.exe C:\Windows\System32\cmd.exe
%HOMEDRIVE% C: C:
%HOMEPATH% \Documents and Settings\{username}
\Users\{username}
Windows Command Prompt www.nubielab.com Page 59
%LOCALAPPDATA%
N/A
(but can be manually added
LOCALAPPDATA=%USERPRO
FILE%\Local
Settings\Application Data)
C:\Users\{username}\AppData\Local
%LOGONSERVER% \\{domain_logon_server} \\{domain_logon_server}
%PATH% C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem;{plus program paths}
C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem;{plus program paths}
%PATHEXT% .COM; .EXE; .BAT; .CMD; .VBS; .VBE; .JS ; .WSF; .WSH;
.COM; .EXE; .BAT; .CMD;
.VBS; .VBE; .JS ; .WSF;
.WSH; .MSC
%ProgramData% N/A C:\ProgramData
%ProgramFiles% C:\Program Files C:\Program Files
%ProgramFiles(x86)% 1 C:\Program Files (x86) C:\Program Files (x86)
%PROMPT% Code for current command prompt format,usually $P$G C :>
Code for current command prompt format,usually $P$G C :>
%PSModulePath% N/A %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\
%Public% N/A C:\Users\Public
%SYSTEMDRIVE% C: C:
%SYSTEMROOT% C:\Windows C:\Windows
%TEMP% and %TMP% C:\Documents and Settings\{username}\Local Settings\Temp
C:\Users\{Username}\AppData\Local\Temp
%USERDOMAIN% {userdomain} {userdomain}
%USERNAME% {username} {username}
%USERPROFILE% %SystemDrive%\Documents and Settings\{username}
%SystemDrive%\Users\{username}
%WINDIR% C:\Windows C:\Windows
1 Only on 64 bit systems, is used to store 32 bit programs.
By default, files stored under Local Settings do not roam with a roaming profile.
%ERRORLEVEL% is a dynamic variable that is automatically set when a program exits.
Dynamic Variables There are also 6 dynamic environment variables, these are computed each time the variable is
expanded.
n.b. you should not attempt to directly SET a dynamic variable.
%CD% - The current directory (string).
%DATE% - The current date using same region specific format as DATE.
%TIME% - The current time using same format as TIME.
%RANDOM% - A random decimal number between 0 and 32767.
%CMDEXTVERSION% - The current Command Processor Extensions version number.
%CMDCMDLINE% - The original command line that invoked the Command Processor.
Pass a variable from one batch script to another Where one batch script CALLs another it is recommended that you SETLOCAL in both scripts
to prevent any possible naming conflicts, so each script should start with:
@ECHO OFF
SETLOCAL
Then to pass a value back to the original calling script, finish the script with a line like: ENDLOCAL & SET _output=%_variable%
In the line above %_variable% is a local variable used and visible within just that one batch
script
%_output% is an output variable that is passed back to the original calling script
Conditional Execution
Syntax
An AND list of commands has the form
command1 && command2
command2 is executed if, and only if, command1 succeeds.
Windows Command Prompt www.nubielab.com Page 60
A single & will always execute both commands
command1 & command2
An OR list of commands has the form
command1 || command2
command2 is executed if, and only if, command1 fails
Example COPY Z:\Oracle\TNSnames.ORA C:\Oracle\ || ECHO The Copy
Failed
Loops and subroutines
There are 2 ways to conditionally process commands in a batch file
IF xxx ELSE yyy - will conditionally perform a command (or a set of commands)
FOR aaa DO xxx - will conditionally perform a command several times (for a set of data, or a
set of files)
Either of these can be combined with the CALL command to run a subroutine like this: @echo off
IF EXIST C:\pagefile.sys CALL :s_page_on_c
IF EXIST D:\pagefile.sys CALL :s_page_on_d
GOTO :eof
:s_page_on_c
echo pagefile found on C: drive
GOTO :eof
:s_page_on_d
echo pagefile found on D: drive
Without the : a second batch file will be called ... @ECHO off
IF EXIST C:\pagefile.sys CALL Second_Batch.cmd
If the code does not need to return then use the GOTO statement like this: @ECHO off
IF EXIST C:\pagefile.sys GOTO s_page_on_c
ECHO pagefile not found
GOTO :eof
:s_page_on_c
ECHO pagefile found
To call a second batch file in a separate shell use CMD An important difference between CALL
and CMD is the exit behaviour if an error occurs. @ECHO off
IF EXIST C:\pagefile.sys CMD /C Second_Batch.cmd
Batch file Functions
Packaging up code into a discrete functions, each with a clear purpose is a very common
programming technique. Re-using known, tested code, means you can solve problems very
quickly by just bolting together a few functions.
The CMD shell does not have any documented support for functions, but you can fake it by
passing arguments/parameters to a subroutine and you can use SETLOCAL to control the
visibility of variables.
At first glance building a function may look as simple as this:
:myfunct
SETLOCAL
SET _var1=%1
SET _var2="%_var1%--%_var1%--%_var1%"
SET _result=%_var2%
ENDLOCAL
but there is a problem, the ENDLOCAL command will throw away the _result variable and so
the function returns nothing.
:myfunct2
SETLOCAL
SET _var1=%1
SET _var2="%_var1%--%_var1%--%_var1%"
ENDLOCAL
SET _result=%_var2%
This version is getting close, but it still fails to return a value, this time because ENDLOCAL
will throw away the _var2 variable
The solution to this is to take advantage of the fact that the CMD shell evaluates variables on a
line-by-line basis - so placing ENDLOCAL on the same line as the SET statement(s) gives the
result we want:
:myfunct3
SETLOCAL
SET _var1=%1
SET _var2="%_var1%--%_var1%--%_var1%"
ENDLOCAL & SET _result=%_var2%
In examples above there are just 2 local variables (_var1 and _var2) but in practice there could
be far more, by turning the script into a function with SETLOCAL and ENDLOCAL we don't
have to worry if any variable names will clash.
In other words you can do this:
Windows Command Prompt www.nubielab.com Page 61
@ECHO OFF SET _var1=64 SET _var2=123 CALL :myfunct3 Testing echo %_var1% echo %_result% goto :eof :myfunct3 SETLOCAL SET _var1=%1 SET _var2="%_var1%--%_var1%--%_var1%" ENDLOCAL & SET _result=%_var2% Using brackets to group expressions
Brackets can be useful to make complex commands more readable and/or to span commands
across several lines. (command)
(
command )
e.g.
IF EXIST C:\pagefile.sys (
ECHO pagefile found on C: drive)
The use of brackets is only required if the command is run over several lines e.g.
IF EXIST filename (
del filename
) ELSE (
echo The file was not found.
)
The CMD shell statement does not use any great intelligence when evaluating brackets used as
part of an IF or a FOR command, so for example the command below will fail:
IF EXIST MyFile.txt (ECHO Some(more)Potatoes) This version will work:
IF EXIST MyFile.txt (ECHO Some[more]Potatoes) You could also escape the extra brackets like (ECHO Some^(more^)Potatoes)
It is worth noting that although brackets are legal in NTFS pathnames, such brackets will be
misinterpreted by the command processor.
Testing Numeric values Do not use brackets or quotes if you are comparing numeric values with an IF command
e.g.
IF (2) GEQ (15) echo "bigger"
or
IF "2" GEQ "15" echo "bigger"
Will perform a character comparison and will echo "bigger"
however the command
IF 2 GEQ 15 echo "bigger"
Will perform a numeric comparison and works as expected.
This is opposite to the SET /a command where quotes are required.
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.
To display current variables:
Type SET without parameters to display all the current environment variables.
Type SET with a variable name to display that variable SET _department
or use ECHO: ECHO [%_department%]
The SET command invoked with a string (and no equal sign) will display a wildcard list of all
matching variables
Display variables that begin with 'P': SET p
Display variables that begin with an underscore SET _
Examples
Storing a text string:
C:\>SET _dept=Sales and Marketing
Windows Command Prompt www.nubielab.com Page 62
C:\>set _
_dept=Sales and Marketing
One variable can be based on another, but this is not dynamic
E.g.
C:\>set xx=fish
C:\>set msg=%xx% chips
C:\>set msg
msg=fish chips
C:\>set xx=sausage
C:\>set msg
msg=fish chips
C:\>set msg=%xx% chips
C:\>set msg
msg=sausage chips
Avoid starting variable names with a number, this will avoid the variable being mis-interpreted
as a parameter
%123_myvar% < > %1 23_myvar
To display undocumented system variables: SET "
Prompt for user input @echo off
Set /P _dept=Please enter Department:
If "%_dept%"=="" goto :sub_error
If /i "%_dept%"=="finance" goto sub_finance
If /i "%_dept%"=="hr" goto sub_hr
goto:eof
:sub_finance
echo You chose the finance dept
goto:eof
:sub_hr
echo You chose the hr dept
The /P switch allows you to set a variable equal to a line of input entered by the user.
The PromptString is displayed before the user input is read. The PromptString can be empty.
The CHOICE command is an alternative to SET /P
To place the first line of a file into a variable:
Set /P _MyVar=<MyFilename.txt
CALL SET
SET can be CALLed allowing a variable substring to be evaluated: SET start=10
SET length=9
SET string=The quick brown fox jumps over the lazy dog
CALL SET substring=%%string:~%start%,%length%%%
ECHO (%substring%)
Deleting an environment variable
Type SET with just the variable name and an equals sign:
SET _department=
Better still, to be sure there is no trailing space after the = use:
(SET _department=)
or
SET "_department="
Variable names can include Spaces
A variable can contain spaces and also the variable name itself may contain spaces, therefore the
following assignment:
SET my var=MyText
will create a variable called "my var"
Similarly
SET _var =MyText
will create a variable called "_var " - note trailing space
To avoid problems with extra spaces appearing in your output, issue SET statements in
parentheses, like this
(SET _department=Some Text)
Alternatively you can do
SET "_department=Some Text"
Note: if you wanted to actually include a bracket in the variable you need to use an escape
character.
The SET command will set ERRORLEVEL to 1 if the variable name is not found in the current
environment.
This can be detected using the IF ERRORLEVEL command
Arithmetic expressions (SET /a)
The expression to be evaluated can include the following operators: Multiply *
Divide /
Add +
Subtract -
Modulus %
Windows Command Prompt www.nubielab.com Page 63
AND &
OR |
XOR ^
LSH <<
RSH >>
Multiply Variable *=
Divide Variable /=
Add Variable +=
Subtract Variable -=
AND Variable &=
OR Variable |=
XOR Variable ^=
LSH Variable <<=
RSH Variable <<=
SET /a calculations Enclose any logical expressions in "quotes"
Several calculations can be put on one line if separated with commas.
Warning: any SET /A calculation that returns a fractional result will be rounded down to the
nearest whole integer.
Examples: SET /A _result=2+4
(=6)
SET /A _result=5
(=5)
SET /A _result+=5
(=10)
SET /A _result="2<<3"
(=16) { 2 Lsh 3 = binary 10 Lsh 3 = binary 10000 = decimal
16 }
SET /A _result="5%%2"
(=1) { 5/2 = 2 + 2 remainder 1 = 1 }
Modulus operator - note that in a batch script, (as opposed to on the command-line), you need to
double up the % to %%
SET /A will treat any character string in the expression as an environment variable name. This
allows you to do arithmetic with environment variable values without having to type any % signs
to get the values. SET /A _result=5 + _MyVar
Leading Zero will specify Octal
Numeric values are decimal numbers, unless prefixed by
0x for hexadecimal numbers,
0 for octal numbers.
So 0x12 = 022 = 18 decimal
The octal notation can be confusing - all numeric values that start with zeros are treated as octal
but 08 and 09 are not valid numbers because 8 and 9 are not valid octal digits.
This is often a cause of error when performing date arithmetic. For example SET /a _day=07 will
return the value=7, but SET /a _day=09 will return an error.
Permanent Changes
Changes made using the SET command are NOT permanent, they apply to the current CMD
prompt only and remain only until the CMD window is closed.
To permanently change a variable at the command line use SetX
or in the GUI - Control Panel, System, Environment, System/User Variables
Changing a variable permanently with SetX will not affect any CMD prompt that is already
open.
Only new CMD prompts will get the new setting.
You can of course use SetX in conjunction with SET to change both at the same time, but neither
SET or SetX will affect other CMD sessions that are already running. When you think about it -
this is a good thing.
It is also possible (although undocumented) to add permanent env variables to the registry
[HKEY_CURRENT_USER\Environment]
(using REGEDIT)
System Environment variables can also be found in
[HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
Autoexec.bat
Any SET statement in c:\autoexec.bat may be parsed at boot time
Variables set in this way are not available to 32 bit gui programs - they won't appear in the
control panel.
They will appear at the CMD prompt.
If autoexec.bat CALLS any secondary batch files, the additional batch files will NOT be parsed
at boot.
This behaviour can be useful on a dual boot PC.
If Command Extensions are disabled all SET commands are disabled other than simple
assignments like:
_variable=MyText
Redirection
Windows Command Prompt www.nubielab.com Page 64
command > filename Redirect command output to a file
command >> filename APPEND into a file
command < filename Type a text file and pass the text
to command
commandA | commandB Pipe the output from commandA into
commandB
commandA & commandB Run commandA and then run commandB
commandA && commandB Run commandA, if it succeeds then
run commandB
commandA || commandB Run commandA, if it fails then run
commandB
Numeric handles:
STDIN = 0 Keyboard input
STDOUT = 1 Text output
STDERR = 2 Error text output
UNDEFINED = 3-9
command 2> filename Redirect any error message into a
file
command 2>> filename Append any error message into a
file
(command)2> filename Redirect any CMD.exe error into a
file
command > file 2>&1 Redirect errors and output to one
file
command > file 2<&1 Redirect output and errors to one
file
command > fileA 2> fileB Redirect output and errors to
separate files
command 2>&1 >filename This will fail!
Redirect to NUL (hide errors)
command 2> nul Redirect error messages to NUL
command >nul 2>&1 Redirect error and output to NUL
command >filename 2> nul Redirect output to file but
suppress error
(command)>filename 2> nul Redirect output to file but
suppress CMD.exe errors
Note, any long filenames must be surrounded in "double quotes". A CMD error is an error raised
by the command processor itself rather than the program/command.
Redirection with > or 2> will overwrite any existing file.
You can also redirect to a printer with > PRN or >LPT1
To prevent the > and < characters from causing redirection, escape with a caret: ^> or ^<
Examples of redirection: DIR >MyFileListing.txt
DIR /o:n >"Another list of Files.txt"
ECHO y| DEL *.txt
ECHO Some text ^<html tag^> more text
MEM /C >>MemLog.txt
Date /T >>MemLog.txt
SORT < MyTextFile.txt
SET _output=%_missing% 2>nul
DIR C:\ >List_of_C.txt 2>errorlog.txt
FIND /i "Jones" < names.txt >logfile.txt
DIR C:\ >List_of_C.txt & DIR D:\ >List_of_D.txt
ECHO DIR C:\ ^> c:\logfile.txt >NewScript.cmd
(TYPE logfile.txt >> newfile.txt) 2>nul
top related