SlideShare a Scribd company logo
Windows Command Prompt   www.nubielab.com   Page 1
ADDUSERS.exe                                                                                                                         an account with the same SID.
Automate the creation of a large number of users                                                     This option will not erase built-in accounts.
Syntax
Create Users:                                                                                          Password_options
                 AddUsers /c filename [/s:x] [/?] Domain                                                  /p:             - Set account creation options, used along with
Password_options                                                                                     any combination of the following:
  Dump to file:                                                                                               * l         - Users do not have to change passwords at next
                 AddUsers /d{:u} filename [/s:x] [/?] Domain                                         logon.
Password_options                                                                                              * c         - Users cannot change passwords.
  Erase Users:                                                                                                * e         - Passwords never expire. (implies l option)
                 AddUsers /e filename [/s:x] [/?] Domain                                                      * d         - Accounts disabled.
Password_options                                                                                                              By default, all created users are required to
key                                                                                                  change their password at logon.
                                                                                                     Example
   Filename          - The comma-delimited file that AddUsers uses for                               Create a comma-delimited text file, which contains the new users to be created. Following the
data.                                                                                                Syntax as follows:
                                                                                                     [Users]
   /s:x              - Change the delimiter character used in filename                               User Name,Full name, Password, Description, HomeDrive, Homepath, Profile, Script
to x.                                                                                                e.g.
                                                e.g. /s:~ would make the                             [User]
delimiter "~"                                                                                        jimmye,James Edward Phillip II,,,,,,
                                                                                                     alexd,Alex Denuur,,,E:,E:usersalexd,,
   Domain            - Query the Primary Domain Controller (PDC) of                                  ronj,Ron Jarook,ChangeThis,,E:,E:usersronj,,
domain.                                                                                              sarahs,Sarah Smith,,,,,,
                You can also use Servername to specify the                                         u0123,Mike Olarte,,,,,,
machine where user accounts are created or read.                                                     Save the file as C:Users.txt and execute the command
                AddUsers will use the local computer by default                                      AddUsers MyDomain /c c:Users.txt /p:e
(if you do not specify Domain)

   /c         - Create user accounts, local groups, and global
                                                                                                     ARP.exe
                                                                                                     ARP - Address Resolution Protocol
groups as specified by filename.
                                                                                                     Display and modify the IP-to-Physical address translation tables used by address resolution
     /d{:u}           - Dump user accounts, local groups, and global
                                                                                                     protocol.
groups to filename.
                                                                                                     Syntax
The (:u) is an optional switch that causes current accounts to be written to the specified file in       View the contents of the local ARP cache table
Unicode text format. Choosing to dump current user accounts does not save the account's                        ARP -a [ip_addr] [-N if_addr]
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           Add a static Arp entry for frequent accessed hosts
create accounts, all passwords of newly created accounts will be empty. To back up security                 ARP -s ip_addr eth_addr [if_addr]
information for accounts, use a Tape Backup.
     /e               - Erase the user accounts specified in the file                                    Delete an entry
name.                                                                                                       ARP -d ip_addr [if_addr]
                         CAUTION: Be careful when erasing user accounts,
as it is not possible to recreate


Windows Command Prompt                                                           www.nubielab.com                                                                                             Page 2
Key                                                                                                Syntax
      -a               Display current ARP entries.                                                   ASSOC .ext = [fileType]
                       May include more than one network interface.                                   ASSOC
                       If ip_addr is specified, the IP and Physical                                   ASSOC .ext
                       addresses for only the specified computer are                                  ASSOC .ext =
displayed.
   -g                  Same as -a.                                                                 Key
                                                                                                         .ext            : The file extension
   -N if_addr   Display the ARP entries for the network                                                  fileType : The type of file
interface specified                                                                                A file extension is the last few characters in a FileName after the period.
                by if_addr.                                                                        So a file called JANUARY.HTML has the file extension .HTML

      -d ip_addr       Delete the host specified by ip_addr.                                       The File extension is used by Windows NT to determine the type of information stored in the file
                       -d * will delete all hosts.                                                 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.
   -s                  Add the host and associates the Internet address
ip_addr                                                                                            More than one file extension may be associated with the same File Type.
                with the Physical address eth_addr. The                                            e.g. both the extension .JPG and the extension .JPEG may be associated with the File Type
Physical address is                                                                                "jpegfile"
                given as 6 hexadecimal bytes separated by
hyphens. The entry                                                                                 At any one time a given file extension may only be associated with one File Type.
                is permanent.                                                                      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
      eth_addr         Specifies a physical address.                                               restore the association to "jpegfile"
   if_addr             If present, this specifies the Internet address                             File Types can be displayed in the Windows Explorer GUI: [View, Options, File Types]
of the                                                                                             however the spelling is usually different to that expected by the ASSOC command e.g. the File
                       interface whose address translation table should                            Type "txtfile" is displayed in the GUI as "Text Document"and "jpegfile" is displayed as
be modified.                                                                                       "image/jpeg"
                         If not present, the first applicable interface
will be used.                                                                                      The command ASSOC followed by just a file extension will display the current File Type for
If two hosts on the same sub-net cannot ping each other successfully, try running ARP -a to list   that extension.
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            ASSOC without any parameters will display all the current file associations.
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.                    ASSOC with ".ext=" will delete the association for that file extension.
Examples                                                                                           Did you leave the Always Use This Program To Open This File option turned on?
Display the ARP cache tables for all interfaces:                                                   To change it back so it prompts you to specify a program each time, just delete the association
C:> arp -a                                                                                        for that file type
Display the ARP cache table for the interface on IP address 10.1.4.99:                             ASSOC .ext=
C:> arp -a -N 10.1.4.99                                                                           [where .ext is the file extension].
Add a static ARP cache entry on IP addr 10.1.4.77 to the physical address 00-AA-21-4A-2F-9A:       Now when you double-click on a file of that type, the system will ask you what program you
C:> arp -s 10.1.4.77 00-AA-21-4A-2F-9A                                                            want to use.
ASSOC
Display or change the association between a file extension and a fileType                          Using the ASSOC command will edit values stored in the registry at HKey_Classes_Root.<file
Windows Command Prompt                                                        www.nubielab.com                                                                                               Page 3
extension>                                                                                                  /q            : Quiet - Suppress interactive prompts.
Therefore it's possible to use registry permissions to protect a file extension and prevent any file        /f            : Force - Force overwrite or delete without
association changes.                                                                                   questions.
                                                                                                            /d            : Delete - Delete the association.
Examples:                                                                                              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
Viewing file associations:
                                                                                                       The File extension is used by Windows NT to determine the type of information stored in the file
ASSOC .txt                                                                                             and therefore which application(s) will be able to display the information in the file. File
ASSOC .doc                                                                                             extensions are not case sensitive and are not limited to 3 characters.
ASSOC >backup.txt
                                                                                                       Example: adding a File Association
Editing file associations:
                                                                                                       To add the File Type "SQLfile"=Notepad.exe and also set the File Association of
ASSOC .txt=txtfile                                                                                     .SQL="SQLfile" run this command:
ASSOC .DIC=txtfile
ASSOC .html=Htmlfile                                                                                   ASSOCIATE .SQL Notepad.exe

Deleting a file association:                                                                           Example: Removing a File Association

ASSOC .html=                                                                                           ASSOCIATE .SQL /d
Repair .REG and .EXE file associations:
ASSOC .EXE=exefile                                                                                     Note that /d will delete the File Association but will NOT delete the File Type.
ASSOC .REG=regfile
Digging through CLASSES_ROOT entries often reveals more than one shell for the same                    File types created by Associate.exe are always given a name in the form xxxfile, where xxx is
application, for example the Apple Quick Time player has two entries, one to "open" (which             the file extension.
gives an annoying nag screen) and one to just "play" the QT file:                                      ATTRIB.exe
[HKEY_CLASSES_ROOTMOVFileshellopen] and [play]                                                      Display or change file attributes. Find Filenames.
In cases like this you can change the default action e.g.                                              Syntax
[HKEY_CLASSES_ROOTMOVFileshell]                                                                                ATTRIB [ + attribute | - attribute ] [pathname] [/S [/D]]
@="play"
                                                                                                       Key
                                                                                                               +       : Turn an attribute ON
ASSOCIATE.exe (Resource Kit)                                                                                   -       : Clear an attribute OFF
One step file association.
                                                                                                        pathname : Drive and/or filename e.g. C:*.txt
This utility does the job of both ASSOC and FTYPE, in one step. ASSOCIATE assigns an                       /S    : Search the pathname including all subfolders.
extension directly with an executable application. This is done by automatically adding a new              /D    : Process folders as well
FileType to the system registry.
Syntax                                                                                                       attributes:
          ASSOCIATE .ext filename [/q /d /f]
                                                                                                                   R    Read-only (1)
Key                                                                                                                H    Hidden (2)
      .ext     : Extension to be associated.                                                                       A    Archive (32)
      filename : Executable program to associate .ext with.                                                        S    System (4)

Windows Command Prompt                                                           www.nubielab.com                                                                                              Page 4
because Windows Explorer will be forced to request the Desktop.ini of every sub-folder to see if
     extended attributes:                                                                               any special folder settings need to be set.
             E Encrypted
             C Compressed (128:read-only)                                                               Viewing archive attributes
             I Not content-indexed
             L Symbolic link/Junction (64:read-only)                                                    The Archive attribute (A) is used to mark files that have changed since they were previously
             N Normal (0: cannot be used for file selection)                                            backed up. The (A) flag is automatically updated by Windows as the file is saved.
             O Offline
             P Sparse file                                                                              If the (A) flag is present - the file is new or has been changed since the last backup.
             T Temporary
The numeric values may be used when changing attributes with VBS/WSH                                    The MSBACKUP, RESTORE, and XCOPY commands use these Archive attributes, as do many
If no attribute is specified attrib will return the current attribute settings. Used with just the /S   (but not all) 3rd party backup solutions.
option ATTRIB will quickly search for a particular filename.                                            Constants - the following attribute values are returned by the GetFileAttributes function:
                                                                                                        FILE_ATTRIBUTE_READONLY = 1
Hidden and System attributes take priority.                                                             FILE_ATTRIBUTE_HIDDEN = 2
                                                                                                        FILE_ATTRIBUTE_SYSTEM = 4
If a file has both the Hidden and System attributes set, you can clear both attributes only with a      FILE_ATTRIBUTE_DIRECTORY = 16
single ATTRIB command.                                                                                  FILE_ATTRIBUTE_ARCHIVE = 32
                                                                                                        FILE_ATTRIBUTE_ENCRYPTED = 64
For example, to clear the Hidden and System attributes for the RECORD.TXT file, you would               FILE_ATTRIBUTE_NORMAL = 128
type:                                                                                                   FILE_ATTRIBUTE_TEMPORARY = 256
ATTRIB -S -H RECORD.TXT                                                                                 FILE_ATTRIBUTE_SPARSE_FILE = 512
                                                                                                        FILE_ATTRIBUTE_REPARSE_POINT = 1024
File Attributes                                                                                         FILE_ATTRIBUTE_COMPRESSED = 2048
                                                                                                        FILE_ATTRIBUTE_OFFLINE = 4096
You can use wildcards (? and *) with the filename parameter to display or change the attributes         FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192
for a group of files.
                                                                                                        BCDBOOT.exe (Windows 7 /2008)
Remember that, if a file has the System or Hidden attribute set, you must clear that attribute          Set up a system partition, repair the boot environment located on the system partition.
before you can change any other attributes.                                                             Syntax
                                                                                                                 BCDBOOT source [/l locale] [/s volume-letter]
Directory Attributes                                                                                                  [/v] [/m [{OS Loader GUID}]]

You can display or change the attributes for a directory/folder. To use ATTRIB with a directory,        Options
you must explicitly specify the directory name; you cannot use wildcards to work with
directories.                                                                                               source The location of the Windows directory to use as the
For example, to hide the directory C:SECRET, you would type the following:                             source for
                                                                                                                   copying boot-environment files.
ATTRIB +H C:SECRET
                                                                                                            /l           The locale. default = US English.
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            /s           The volume letter of the system partition.
and System attributes are used by Windows Explorer to determine whether the folder is a special                          The default is the system partition identified by the
folder, such as My Documents, Favorites, Fonts, etc.                                                    firmware.
Setting the Read-Only attribute on a folder can affect performance, particularly on shared drives
Windows Command Prompt                                                               www.nubielab.com                                                                                             Page 5
/v          Enable verbose mode                                                                        BOOTCFG /raw                 Add OS load options, specified as a
                                                                                                  string
    /m            By default, merge only global objects.
                  If an OS Loader GUID is specified, merge the given                                    BOOTCFG /rebuild                Totally rebuild boot.ini (use when
loader object within                                                                              Windows won't start)
                  the system template to produce a bootable entry.
BCDboot may also be run from Windows PE (Preinstallation Environment)                                      BOOTCFG /rmsw                Remove OS load options for an OS
Examples
Initialize the system partition using files from the operating system image installed on the C:             BOOTCFG /timeout Change the OS time-out value.
volume:                                                                                           Detailed options for all the above are available from BOOTCFG /? Items in bold are only
C:> bcdboot C:Windows                                                                           available from the recovery console
Set the default BCD locale to Japanese, and copy BCD (Boot Configuration Data) files to drive     Default identification strings:
S:                                                                                                OS Load Options = /Fastdetect
C:> bcdboot C:Windows /l ja-jp /s S:                                                            Load Identifier = Microsoft Windows XP Professional
Merge the OS loader in the current BCD store identified with the given GUID in the new BCD        If you intend to rebuild the boot.ini file, delete it first - boot into the recovery console then:
store:                                                                                              ATTRIB -H -R -S C:Boot.ini
C:> bcdboot c:windows /m {d58d10c6-df53-11dc-878f-00064f4f4e08}                                   DEL C:Boot.ini
                                                                                                    Bootcfg /Rebuild
BOOTCFG.exe                                                                                         Fixboot
Edit the Windows boot settings stored in Boot.ini
Syntax                                                                                            CACLS.exe
         BOOTCFG /addsw            Add OS load options for an OS entry in                         Display or modify Access Control Lists (ACLs) for files and folders.
boot.ini
                                                                                                  Access Control Lists apply only to files stored on an NTFS formatted drive, each ACL
      BOOTCFG /copy                Duplicate the entries for an OS                                determines which users (or groups of users) can read or edit the file. When a new file is created it
instance.                                                                                         normally inherits ACL's from the folder where it was created.
                                                                                                  Syntax
         BOOTCFG /dbg1394          Configure 1394 port debugging                                          CACLS pathname [options]

         BOOTCFG /debug            Edit the debug settings for an OS.                             Options:

         BOOTCFG /default          Specify the default OS                                             /T      Search the pathname including all subfolders.
                                                                                                      /E      Edit ACL (leave existing rights unchanged)
      BOOTCFG /delete              Delete an OS entry [operating systems]                             /C      Continue on access denied errors.
section of Boot.ini
                                                                                                      /G user:permission
      BOOTCFG /ems      Redirect the EMS console to a remote                                               Grant access rights, permision can be:
computer (server only).                                                                                           R Read
                        (Emergency Management Services)                                                      W Write
                                                                                                             C Change (read/write)
         BOOTCFG /list             List entries in boot.ini                                                  F Full control

         BOOTCFG /query            Display section entries from Boot.ini                              /R user



Windows Command Prompt                                                        www.nubielab.com                                                                                                    Page 6
Revoke specified user's access rights (only valid with                                             /E /R to remove ACL rights for the user concerned, then use /E to add the desired
/E).                                                                                                          rights.
                                                                                                          The /T option will only traverse subfolders below the current directory.
    /P user:permission                                                                              If no options are specified CACLS will display the current ACLs
         Replace access rights, permission can be:                                                  e.g. To display the current folder
           N None                                                                                   CACLS .
           R Read                                                                                   Display permissions for one file
           W Write                                                                                  CACLS MyFile.txt
           C Change (read/write)                                                                    Display permissions for multiple files
           F Full control                                                                           CACLS *.txt
     /D user                                                                                        Inherited folder permissions are displayed as:
             Deny access to user.                                                                     OI - Object inherit                - This folder and files. (no inheritance
In all the options above "user" can be a UserName or a Workgroup (either local or global)           to subfolders)
                                                                                                      CI - Container inherit - This folder and subfolders.
You can specify more than one user:permission in a single command. Wildcards can be used to           IO - Inherit only                  - The ACE does not apply to the current
specify multiple files.                                                                             file/directory
If a UserName or WGname includes spaces then it must be surrounded with quotes e.g.
"Authenticated Users"                                                                               These can be combined as folllows:
                                                                                                      (OI)(CI)                   This folder, subfolders, and files.
If no options are specified CACLS will display the ACLs for the file(s)                               (OI)(CI)(IO) Subfolders and files only.
Setting Deny permission (/D) will deny access to a user even if they also belong to a group that            (CI)(IO) Subfolders only.
grants access.                                                                                        (OI)         (IO) Files only.
Limitations                                                                                         So BUILTINAdministrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F'
Cacls cannot display or modify the ACL state of files locked in exclusive use.                      (Fullcontrol)
Cacls cannot set the following permissions: change permissions, take ownership, execute, delete     similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)
use XCACLS to set any of these.                                                                     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.
Using CACLS                                                                                         Errors when changing permissions
     The CACLS command does not provide a /Y switch to automatically answer 'Y' to the             If a user or group has a permission on a file or folder and you grant a second permission to the
       Y/N prompt. However, you can pipe the 'Y' character into the CACLS command using             same user/group on the same folder, NTFS will sometimes produce the error message "The
       ECHO, use the following syntax:                                                              parameter is incorrect" To fix this (or prevent it happening) revoke the permission first (/e /r) and
                                                                                                    then reapply (/e /g)
        ECHO Y| CACLS /g <username>:<permission>                                                    Examples:

                                                                                                    Add Read-Only permission to a single file
       To edit a file you must have the "Change" ACL (or be the file's owner)                      CACLS myfile.txt /E /G "Power Users":R
       To use the CACLS command and change an ACL requires "FULL Control"                          Add Full Control permission to a second group of users
       File "Ownership" will always override all ACL's - you always have Full Control over files   CACLS myfile.txt /E /G "FinanceUsers":F
        that you create.                                                                            Now revoke the Read permissions from the first group
                                                                                                    CACLS myfile.txt /E /R "Power Users"
       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       Now give the first group Full-control:
        exists will raise an error. To be sure the CALCS command will work without errors use       CACLS myfile.txt /E /G "Power Users":F

Windows Command Prompt                                                         www.nubielab.com                                                                                                  Page 7
Give the Finance group Full Control of a folder and all sub folders                                    At the end of the subroutine, GOTO :eof will return to the position where you used CALL.
CACLS c:docswork /E /T /C /G "FinanceUsers":F
                                                                                                       Example
                                                                                                          @ECHO OFF
CALL                                                                                                      SETLOCAL
Call one batch program from another.                                                                      CALL :s_staff SMITH 100
Syntax                                                                                                    GOTO s_last_bit
         CALL [drive:][path]filename [parameters]
                                                                                                           :s_staff
         CALL :label [parameters]                                                                          ECHO Name is %1
                                                                                                           ECHO Rate is %2
         CALL internal_cmd                                                                                 GOTO :eof
Key:                                                                                                      :s_last_bit
   pathname             The batch program to run                                                          ECHO The end of the script
                                                                                                       Advanced usage : CALLing internal commands
    parameters          Any command-line arguments
                                                                                                       In addition to the above, CALL can also be used to run any internal command (SET, ECHO etc)
    :label              Jump to a label in the current batch script.
                                                                                                       and also expand any environment variables passed on the same line.
     internal_cmd Any internal command, first expanding any
                                                                                                       For example
variables in the argument
                                                                                                           @ECHO off
CALL a second batch file                                                                                   SETLOCAL
The CALL command will launch a new batch file context along with any specified arguments.                  set server1=frodo3
When the end of the second batch file is reached (or if EXIT is used), control will return to just         set server2=gandalf4
after the initial CALL statement.                                                                          set server3=ascom5
CALL a subroutine (:label)                                                                                 set server4=last1
The CALL command will pass control to the statement after the label specified along with any
specified arguments .                                                                                      ::run the Loop for each of the servers
To exit the subroutine specify GOTO:eof this will transfer control to the end of the current               call :loop server1
subroutine.                                                                                                call :loop server2
Arguments can be passed either as a simple string or using a variable:                                     call :loop server3
CALL MyScript.cmd "1234"                                                                                   call :loop server4
CALL OtherScript.cmd %_MyVariable%                                                                         goto:eof

Use a label to CALL a subroutine                                                                           :loop
                                                                                                           set _var=%1
A label is defined by a single colon followed by a name. This is the basis of a batch file function.       :: Evaluate the server name
CALL :s_display_result 123                                                                                 CALL SET _result=%%%_var%%%
ECHO Done                                                                                                  echo The server name is %_result%
GOTO :eof                                                                                                  goto :eof
:s_display_result
ECHO The result is %1                                                                                      :s_next_bit
GOTO :eof                                                                                                  :: continue below


Windows Command Prompt                                                           www.nubielab.com                                                                                             Page 8
:: Note the line shown in bold has three '%' symbols                                                   Moving down the folder tree with a reference RELATIVE to the
:: The CALL will expand this to: SET _result=%server1%                                              current folder...
Each CALL does one substitution of the variables. (You can also do CALL CALL... for multiple           C:windows> CD java
substitutions)                                                                                         C:windowsjava>
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.       Moving up and down the folder tree in one command...
If Command Extensions are disabled, the CALL command will not accept batch labels.                      C:windowsjava> CD ..system32
                                                                                                        C:windowssystem32>
                                                                                                    If Command Extensions are enabled the CD command is enhanced as follows:
CD
Change Directory - Select a Folder (and drive)                                                      1) The current directory string is converted to use the correct CASE.
Syntax                                                                                              So CD C:wiNnt would actually set the current directory to C:Winnt
       CD [/D] [drive:][path]
       CD [..]                                                                                      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.
Key
   /D : change the current DRIVE in addition to changing folder.                                    For example:
Examples                                                                                            cd My folder
   To change to the parent directory.
   C:Work> CD ..                                                                                   is the same as:
                                                                                                    cd "My folder"
      To change to the grant-parent directory.                                                      3) An asterisk can be used to complete a folder name
      C:WorkbackupJanuary> CD ....                                                              e.g. from C:

      To change to the ROOT directory.                                                              C:> CD pro*
      C:WorkbackupJanuary> CD                                                                   will move to
                                                                                                    C:Program Files
      To display the current directory in the specified drive.
      C:> CD D:                                                                                    CHDIR is a synonym for CD

      To display the current drive and directory.                                                   Tab Completion
      C:Work> CD
                                                                                                    This allows changing current folder by entering part of the path and pressing TAB
      To display the current drive and directory.                                                        C:> CD Prog [PRESS TAB]
      C:Work> ECHO "%CD%"                                                                               Will go to C:Program Files
                                                                                                    Tab Completion is disabled by default, it has been known to create difficulty when using a batch
   In a batch file to display the location of the batch script                                      script to process text files that contain TAB characters.
file (%0)
   C:> ECHO "%~dp0"                                                                                Tab Completion is turned on by setting the registry value shown below
   Moving down the folder tree with a full path reference to the                                    REGEDIT4
ROOT folder...                                                                                      [HKEY_CURRENT_USERSoftwareMicrosoftCommand Processor]
   C:windows> CD windowsjava                                                                     "CompletionChar"=dword:00000009
   C:windowsjava>                                                                                 Changing the Current drive


Windows Command Prompt                                                        www.nubielab.com                                                                                                  Page 9
simply enter the drive letter followed by a colon                                              Example:
C:> E:
E:>                                                                                            CHKDSK C: /F
                                                                                               Fixing Errors /F
To change drive and directory at the same time, use CD with the /D switch
C:> cd /D E:utils                                                                             If the drive is the boot partition, you will be prompted to run the check during the next boot
E:utils>
                                                                                               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.
chkdsk.exe                                                                                     If you use chkdsk /f on a disk with a very large number of files (millions), chkdsk may take a
Check Disk - check and repair disk problems                                                    long time to complete.
Syntax
                                                                                               When you delete a file or folder that has 'custom' permissions, the ACL is not deleted, it is
       CHKDSK [drive:][[path]filename] [/F] [/V] [/R] [/L[:size]]
                                                                                               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)
Key
                                                                                               option to correct these."
      [drive:]       The drive to check.
                                                                                               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.
      filename       File(s) to check for fragmentation (FAT only).

      /F             Automatically Fix file system errors on the disk.                         Scan only (without /f switch)

   /X                Fix file system errors on the disk, (Win2003 and                          If a file needs to be fixed chkdsk will alert you with a message but will not fix the error(s).
above)
                     dismounts the volume first, closing all open file                         chkdsk may report lost allocation units on the disk - it will produce this report even if the files
handles.                                                                                       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
      /R             Scan for and attempt Recovery of bad sectors.                             report errors when none are present. To avoid this, close all programs or processes that have
                                                                                               open handles to the volume.
   /V                Display the full path and name of every file on                           On computers running Windows 2003 SP1, chkdsk automatically creates a shadow copy, so you
the disk.                                                                                      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
   /L:size    NTFS only: change the log file size to the                                       volume, making data unavailable.
specified number of kilobytes.                                                                 Run at Bootup
              If size is not specified, displays the current log                               Running at bootup is often the easiest way to close all open file handles.
size and the drive type                                                                        Use the GUI, chkntfs or the FSUTIL dirty commands to set or query the volumes 'dirty' bit so
              (FAT or NTFS).                                                                   that Windows will run chkdsk when the computer is restarted.
                                                                                               Event Logs
      /C             Skip directory corruption checks.                                         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 -
   /I          Skip corruption checks that compare directory                                   Application Log.
entries to the                                                                                 Cluster (or block) Size
               file record segment (FRS) in the volume's master
file table (MFT)                                                                               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 10
When the cluster size is greater than 4 KB on an NTFS volume, none of the NTFS compression
functions are available.                                                                               /T : Change the Autochk.exe initiation countdown time (time
Exit codes                                                                                          in seconds)
                                                                                                            If you don't specify Time: displays the current
0 No errors were found                                                                              countdown time.
1 Errors were found and fixed.
2 Could not check the disk, did not or could not fix errors.                                              /D : Restore the machine to the default behavior; all drives
Notes:                                                                                              are
Consider the time required to run Chkdsk to repair any errors that occur. Chkdsk times are                      checked at boot time and chkdsk is run on those that are
determined by the number of files on the volume and by the number of files in the largest folder.   dirty.
Chkdsk performance under Windows 2003 is around 30% faster than previous versions.                               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.
To issue chkdsk on a hard drive you must be a member of the Administrators group.                   /T option is new in Win XP
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:

HKLMSystemCurrentControlSetControlSession Manager
REG_DWORD:AutoChkTimeOutData                                                                        CHOICE.exe (Resource Kit/Standard Vista command)
The value is the time in seconds that you want CHKDSK to wait (0 = no delay) default is 10          Accept user input to a batch file.
seconds.
Chkdsk is also available from the Recovery Console (with different parameters.)                     Choice allows single key-presses to be captured from the keyboard.
Disk Errors                                                                                         Syntax
"The file system structure on the disk is corrupt and unusable"                                          CHOICE [/C[:]choiceKeys] [/N] [/S] [/T[:]k,nn] [text]
If you have disk corruption, run the drive manufacturers diagnostics:
Toshiba | Hitachi | ibm | Seagate/Maxtor/Freeagent | Western digital                                Key
                                                                                                       /C[:]choiceKeys           : One or more keys the user can press.
                                                                                                    Default is YN
CHKNTFS.exe                                                                                            /N                        : Do not display choiceKeys at end of prompt
Check the NTFS file system with CHKDSK                                                              string.
Syntax                                                                                                 /S                        : case Sensitive.
        CHKNTFS drive: [...]                                                                           /T[:]k,dd                 : Default the choice to k after dd seconds
        CHKNTFS /C drive: [...]                                                                        text                      : Message string to display the choices
        CHKNTFS /X drive: [...]                                                                     available
        CHKNTFS /t[:Time]
        CHKNTFS /D                                                                                  The Windows 2003 version has some slight differences:

Key                                                                                                     CHOICE [/c [choiceKeys]] [/N] [/CS] [/t Timeout /d Choice]
      drive : Specifies a drive letter.                                                             [/m Text]

      /C : Check - schedules chkdsk to be run at the next reboot.                                   key
                                                                                                       /C[:]choiceKeys : One or more keys the user can press.
   /X : Exclude a drive from the default boot-time check.                                           Default is YN
        Excluded drives are not accumulated between command                                            /N              : Do not display choiceKeys at end of prompt
invocations.                                                                                        string.


Windows Command Prompt                                                         www.nubielab.com                                                                                              Page 11
/CS                      :   Case Sensitive.                                                                                   If UserName is not supplied, it will be
   /T dd                    :   Timeout in dd seconds                                                requested.
   /d choiceKey             :   Choice made on Timeout
   /m text                  :   Message string to describe the choices                                  /pass:Password The password to store with this entry. If
available                                                                                            Password is not supplied, it will be requested.

ERRORLEVEL will return the numerical offset of choiceKeys.                                              /delete:                  Delete a user name and password from the
Availability                                                                                         list.
Choice.com was originally supplied on the Windows 95 install CD, however there are some                                           If TargetName is specified, that entry will
issues with this version under NT - multiple concurrent invocations of CHOICE will clobber           be deleted.
each other. CHOICE.com will also burn a lot of CPU's when in a wait state.                                              If /ras is specified, the stored remote
The NT and 2000 Resource Kits contain CHOICE.EXE which behaves a lot better.                         access entry will be deleted.
In Windows 2003 CHOICE became a built-in command so it is no longer in the resource kit.
Examples:                                                                                               /list                     Display the list of stored user names and
                                                                                                     credentials.
CHOICE /C:FH /M select [F] Floppy or [H] Hard drive                                                                              If TargetName is not specified, all stored
IF errorlevel 2 goto s_hard                                                                          user names and credentials will be listed.
IF errorlevel 1 goto s_floppy                                                                        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.
Note the order of the IF statements above, IF errorlevel 1 will return TRUE for an errorlevel of 2
                                                                                                     Examples:
CHOICE can be used to set a specific %errorlevel%
for example to set the %errorlevel% to 6 :                                                           Display a list of stored user names and credentials:
ECHO 6| CHOICE /C:123456 /N >NUL                                                                     cmdkey /list
CMDKEY.exe (Windows 7)                                                                               Add a user name and password for user Kate to access computer Server01 with the password
Create, list or delete stored user names, passwords or credentials.                                  passme, type:
Syntax                                                                                               cmdkey /add:server01 /user:Kate /pass:passme
          cmdkey [{/add:TargetName|/generic:TargetName}]                                             Add a user name for user Kate to access computer Server01 and prompt for the password
               {/smartcard|/user:UserName [/pass:Password]}                                          whenever Server01 is accessed:
                    [/delete{:TargetName|/ras}]                                                      cmdkey /add:server01 /user:Kate
                         /list:TargetName                                                            Delete the stored credential for remote access:
                                                                                                     cmdkey /delete /ras
Key:                                                                                                 Delete the stored credential for Server01:
   /add                     Add a user name and password to the list.                                cmdkey /delete:Server01

   TargetName      The computer or domain name that this entry
will be associated with.
                                                                                                     COLOR
    /generic                Add generic credentials to the list.                                     Sets the default console foreground and background colours.
                                                                                                     Syntax
    /smartcard              Retrieve the credential from a smart card.                                        COLOR [background][foreground]
                                                                                                     Colour attributes are specified by 2 of the following hex digits. Each digit can be any of the
   /user:UserName           The user or account name to store with this                              following values:
entry.
                                                                                                     0 = Black

Windows Command Prompt                                                         www.nubielab.com                                                                                                Page 12
8 = Gray                                                                                           pathname2 The path and filename of the second file(s)

1 = Blue                                                                                           /D               Display differences in decimal format. (default)
9 = Light Blue                                                                                     /A               Display differences in ASCII characters.

2 = Green                                                                                       /L          Display line numbers for differences.
A = Light Green                                                                                 /N=number Compare only the first X number of lines in the
                                                                                             file.
3 = Aqua                                                                                        /C          do a case insensitive string comparison
B = Light Aqua                                                                               Running COMP with no parameters will result in a prompt for the 2 files and any options

4 = Red                                                                                      To compare sets of files, use wildcards in pathname1 and pathname2 parameters.
C = Light Red
                                                                                             When used with the /A option COMP is similar to the FC command but it displays the individual
5 = Purple                                                                                   characters that differ between the files rather than the whole line.
D = Light Purple                                                                             To compare files of different sizes, use /N= to compare only the first n lines (common portion of
                                                                                             each file.)
6 = Yellow
E = Light Yellow                                                                             COMP will normally finish with a Compare more files (Y/N) prompt
                                                                                             to suppress this: ECHO n|COMP <options>
7 = White
F = Bright White

If no argument is given, COLOR restores the colour to what it was when CMD.EXE started.
                                                                                             COPY
                                                                                             Copy one or more files to another location
                                                                                             Syntax
Colour values are assigned in the following order:                                                  COPY source destination [options]
The DefaultColor registry value.                                                                         COPY source1 + source2.. destination [options]
The CMD /T command line switch
The current colour settings when cmd was launched                                            Key
                                                                                                        source :      Pathname for the file or files to be copied.
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.                                         /A   :     ASCII text file (default)
                                                                                                           /B   :     Binary file copy - will copy extended characters.
COMP.exe                                                                                     destination :            Pathname for the new file(s).
Compare two files (or sets of files). Display items which do not match.
Syntax
                                                                                                           /V   :     Verify that the new files were written correctly.
       COMP [pathname1] [pathname2] [/D] [/A] [/L] [/N=number]
[/C]
                                                                                                     /N : If at all possible, use only a short filename
                                                                                             (8.3) when creating
Key
                                                                                                            a destination file. This may be necessary when
      pathname1 The path and filename of the first file(s)
                                                                                             copying between disks


Windows Command Prompt                                                    www.nubielab.com                                                                                           Page 13
that are formatted differently e.g NTFS and VFAT,                                     COPY "C:my worksome file.doc" "D:New docsnewfile.doc"
or when archiving
               data to an ISO9660 CDROM.                                                             Specify the source only, with a wildcard will copy all the files into the current directory:
                                                                                                     COPY "C:my work*.doc"
        /Z :           Copy files in restartable mode. If the copy is
interrupted                                                                                          Specify the source with a wildcard and the destination as a single file, this is generally only
               part way through, it will restart if possible.                                        useful with plain text files.
(use on slow networks)                                                                               COPY "C:my work*.txt" "D:New docscombined.txt"

            /Y    :    Suppress confirmation prompt (Windows 2000 only)                              Quiet copy (no feedback on screen)
                                                                                                     COPY oldfile.doc newfile.doc >nul
            /-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.                                DEL
To force the overwriting of destination files under both NT4 and Windows2000 use the                 Delete one or more files.
COPYCMD environment variable:                                                                        Syntax
SET COPYCMD=/Y                                                                                               DEL [options] [/A:file_attributes] files_to_delete

This will turn off the prompt in Win2000 and will be ignored by NT4 (which overwrites by             Key
default)                                                                                                files_to_delete : This may be a filename, a list of files or
Binary copies                                                                                        a Wildcard
"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.                                                                       options
                                                                                                        /P Give a Yes/No Prompt before deleting.
Combine files                                                                                           /F Ignore read-only setting and delete anyway (FORCE)
To combine files, specify a single file for the destination, but multiple files as the source. To       /S Delete from all Subfolders (DELTREE)
specify more than one file use wildcards or list the files with a + in between each                     /Q Quiet mode, do not give a Yes/No Prompt before deleting.
(file1+file2+file3)
When copying multiple files in this way the first file must exist or else the copy will fail, a            /A   Select files to delete based on file_attributes
workaround for this is COPY null + file1 + file2 dest1
COPY will accept UNC pathnames                                                                       file_attributes:
Copy from the console (accept user input)                                                               R Read-only               -R     NOT   Read-only
COPY CON filename.txt                                                                                   S System                  -S     NOT   System
Then type the input text followed by ^Z (Control key & Z)                                               H Hidden                  -H     NOT   Hidden
To do this in Powershell use the following function:                                                    A Archive                 -A     NOT   Archive
function copycon {
[system.console]::in.readtoend()                                                                     Wildcards: These can be combined with part of a filename
}
Examples:                                                                                               * Match any characters
                                                                                                        ? Match any ONE character
In the current folder                                                                                Examples:
COPY oldfile.doc newfile.doc
                                                                                                     To delete HelloWorld.TXT
Copy from a different folder/directory:                                                              DEL HelloWorld.TXT

Windows Command Prompt                                                            www.nubielab.com                                                                                                  Page 14
you will then be able to delete the file.
To delete "Hello Big World.TXT"                                                                         To cure the problem permanently - Control Panel, Add/Remove programs, Win Accessories,
DEL "Hello Big World.TXT"                                                                               indexing service.
                                                                                                        Delete Locked files (Typically IE temp files or the Offline cache)
To delete all files that start with the letter A                                                        This works on any version of NT, 2000 or XP
DEL A*                                                                                                  Close all applications
                                                                                                        Open a command prompt
To delete all files that end with the letter A                                                          Click Start, and then Shut Down
DEL *A.*                                                                                                Simultaneously press CTRL+SHIFT+ALT.
                                                                                                        While you keep these keys pressed, click Cancel in the Shut Down Windows dialog box.
To delete all files with a .DOC extension                                                               In the command prompt window, navigate to the cache location, and delete all files from the
DEL *.DOC                                                                                               folder (DEL /s)
                                                                                                        At the command prompt, type explorer, and then press ENTER.
To delete all read only files
DEL /a:R *
                                                                                                        DELTREE
To delete all files including any that are read only
DEL /F *                                                                                                Previous versions of Windows had the DELTREE command that deletes all files and sub folders.
                                                                                                        DEL /s will delete all files
Folders                                                                                                 RD /s will remove all files and folders including the root folder.
                                                                                                        :: Remove all files and subfolders but NOT the root folder
If a folder name is given instead of a file, all files in the folder will be deleted, but the folder
                                                                                                        :: From tip 617 at JsiFAQ.com
itself will not be removed.
                                                                                                        @echo off
                                                                                                        pushd %1
Temporary Files
                                                                                                        del /q *.*
You should clear out TEMP files on a regular basis - this is best done at startup when no
                                                                                                        for /f "Tokens=*" %%G in ('dir /B') do rd /s /q "%%G"
applications are running. To delete all files in all subfolders of C:temp but leave the folder
                                                                                                        popd
structure intact:
                                                                                                        Normally DEL will display a list of the files deleted, if Command Extensions are disabled; it will
     DEL /F /S /Q %TEMP%
                                                                                                        instead display a list of any files it cannot find.
When clearing out the TEMP directory it is not generally worthwhile removing the subfolders
                                                                                                        ERASE is a synonym for DEL
too - they don't use much space and constantly deleting and recreating them can potentially
increase fragmentation within the Master File Table.
                                                                                                        DELPROF (Resource Kit)
Deleting a file will not prevent third party utilities from un-deleting it again, however you can       Delete windows user profiles.
turn any file into a zero-byte file to destroy the file allocation chain like this:                     Syntax
                                                                                                                DELPROF [options]
TYPE nul > C:examplesMyFile.txt
DEL C:examplesMyFile.txt                                                                              Key
Undeletable Files                                                                                             /Q        Quiet, no confirmation.
Files are sometimes created with the very long filenames or reserved names: CON, AUX,
COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, NUL                                                            /I        Ignore errors and continue deleting.
To delete these use the syntax: DEL .C:somedirLPT1
Alternatively SUBST a drive letter to the folder containing the file.                                      /P           Prompts for confirmation before deleting each
If a file (or folder) still appears to be 'undeletable' this is often caused by the indexing service.   profile.
Right click the file you need to delete, choose properties, advanced and untick "allow indexing"

Windows Command Prompt                                                               www.nubielab.com                                                                                           Page 15
/C:computer_name
            Delete profiles on a remote computer.                               /O:N   Name                  /O:-N   Name
                                                                                /O:S   file Size             /O:-S   file Size
    /D:Number_of_days                                                           /O:E   file Extension        /O:-E   file Extension
            Only delete profiles that have been inactive for                    /O:D   Date & time           /O:-D   Date & time
            'X' Number of days (or greater)                                     /O:G   Group folders first   /O:-G   Group folders last
                                                                                several attributes may be combined e.g. /O:GEN
    /R          Delete roaming profile cache only ##
                                                                                [time] /T:         the time field to display & use for sorting

## = New in version 5.2 (XP resource kit)                                       /T:C       Creation
Example:                                                                        /T:A       Last Access
                                                                                /T:W       Last Written (default)
delprof /D:14
                                                                                [options]
                                                                                /S     include all subfolders.
                                                                                /R     Display alternate data streams. (Vista and above)
DIR                                                                             /B
                                                                                /L
                                                                                       Bare format (no heading, file sizes or summary).
                                                                                       use Lowercase.
Display a list of files and subfolders
                                                                                /Q     Display the owner of the file.
Syntax
         DIR [pathname(s)] [display_format] [file_attributes]
                                                                                /N         long list format where filenames are on the far right.
[sorted] [time] [options]
                                                                                /X         As for /N but with the short filenames included.
Key
    [pathname] The drive, folder, and/or files to display,
                                                                                /C         Include thousand separator in file sizes.
                       this can include wildcards:
                                                                                /-C        don't include thousand separator in file sizes.
                      *   Match any characters
                                                                                /4        Display four-digit years
                      ?   Match any ONE character
                                                                            The switches above may be preset by adding them to an environment variable called DIRCMD.
                                                                            For example: SET DIRCMD=/O:N /S
   [display_format]
                /P        Pause after each screen of data.
                /W        Wide List format, sorted horizontally.            Override any preset DIRCMD switches by prefixing the switch with -
                /D        Wide List format, sorted by vertical              For example:
column.                                                                     DIR *.* /-S
                                                                            Upper and Lower Case filenames:
    [file_attributes] /A:                                                   Filenames longer than 8 characters - will always display the filename with mixed case as
                                                                            entered.
    /A:D Folder          /A:-D NOT Folder                                   Filenames shorter than 8 characters - may display the filename in upper or lower case - this may
    /A:R Read-only       /A:-R NOT Read-only                                vary from one client to another (registry setting)
    /A:H Hidden          /A:-H NOT Hidden
    /A:A Archive         /A:-A NOT Archive                                  To obtain a bare DIR format (no heading or footer info) but retain all the details, pipe the output
    /A    Show all files                                                    of DIR into FIND, this assumes that your date separator is /
    several attributes may be combined e.g. /A:HD-R                         DIR c:temp*.* | FIND "/"

    [sorted]       Sorted by /O:
Windows Command Prompt                                   www.nubielab.com                                                                                             Page 16
FOR /f "tokens=*" %%G IN ('dir c:temp*.* ^| find "/"') DO echo                                End localisation of environment changes in a batch file. Pass variables from one batch file to
%%G                                                                                             another.
Normally DIR /b will return just the filename, however when displaying subfolders with DIR /b   Syntax
/s the command will return a full pathname.                                                               ENDLOCAL
                                                                                                If SETLOCAL is used to make variables 'local' to one batch script, then those variables will be
Checking filesize during a download (to monitor progress of a large download)                   invisible to all other batch scripts unless explicitly passed using an ENDLOCAL & SET...
   TYPE file_being_downloaded >NUL                                                              command.
   DIR file_being_downloaded                                                                    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.
ECHO                                                                                            Passing variables from one routine to another
Display messages on screen, turn command-echoing on or off.
Syntax                                                                                          The CMD command processor always works on a line-by-line basis, so it will convert all
        ECHO [ON | OFF]                                                                         %variables% into their text values before executing any of the commands.
        ECHO [message]
Key                                                                                             By putting ENDLOCAL & SET commands on a single line you are able to SET a variable just
    ON         : Display each line of the batch on screen (default)                             before the localisation is ended by the ENDLOCAL command.
    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).                   Examples:
                                                                                                ::Sales.cmd
In most batch files you will want ECHO OFF, turning it ON can be useful when debugging a
problematic batch script.                                                                           @Echo off
                                                                                                    SETLOCAL
In a batch file, the @ symbol is the same as ECHO OFF applied to the current line only.                Set _item="Ice Cream Maker"
                                                                                                       Set _price=450
Normally a command is executed and takes effect from the next line onwards, @ is a rare             ENDLOCAL & SET _return1=%_item%& SET _return2=%_price%
example of a command that takes effect immediately.
                                                                                                ::Results.cmd
Command characters will normally take precedence over the ECHO statement
                                                                                                    @Echo off
e.g. The redirection and pipe characters: & < > | ON OFF
                                                                                                    SETLOCAL
                                                                                                    CALL Sales.cmd
To override this behaviour you can escape each command character with ^ as follows:
                                                                                                    Echo [%_return1%] will cost [%_return2%]
    ECHO Nice ^&Easy
    ECHO Salary is ^> Commision
    ECHO Name ^| Username ^| Expiry Date
                                                                                                ::SubDemo.cmd
    ECHO:Off On Holiday
Echo text into a FILE
                                                                                                    @Echo off
                                                                                                    SETLOCAL
The general syntax is
                                                                                                    CALL sub_products
Echo This is some Text > FileName.txt
                                                                                                    Echo [%_return1%] will cost [%_return2%]

ENDLOCAL                                                                                            :sub_products
                                                                                                    SETLOCAL

Windows Command Prompt                                                       www.nubielab.com                                                                                           Page 17
Set _item="Coffee Grinder"                                                                echo %errorlevel%
          Set _price=150                                                                            goto :eof
     ENDLOCAL & SET _return1=%_item%& SET _return2=%_price%                                         :setError
Multiple SET commands may be added to pass multiple variables, just prefix each with an &           exit /B 5
Be aware that any trailing spaces will be added to the variables value.                             To make this more flexible you can change the subroutine to set any errorlevel like this:
Improving readability                                                                               :setError
The 'ENDLOCAL & SET' technique described above can become difficult to read if you have a           exit /B %1
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=^
                                                                                                    EXPAND
  Set _return1=%_item%^&^                                                                           Uncompress one or more compressed files.
  Set _return2=%_price%^&^                                                                          Syntax
  Set _return3=%_discount%^&^                                                                              EXPAND Source Destination
  Set _return4=%_delivery%                                                                                 EXPAND -r Source Destination
                                                                                                           EXPAND -r Source
Endlocal & %_returns%
In these examples we have used the variable names _return1, _return2 etc, but you can use any
                                                                                                    Options
names for the return variables, even re-use the exact same variable name inside and outside the
ENDLOCAL command (SET _price=%_price%)
                                                                                                          Source          : Source filename or a wildcard

EXIT                                                                                                      Destination : Destination filename or folder
Quit the current batch script, quit the current subroutine or quit the command processor
(CMD.EXE) optionally setting an errorlevel code.                                                       -r              : Rename the files
Syntax                                                                                              EXPAND
         EXIT [/B] [exitCode]                                                                       Uncompress one or more compressed files.
                                                                                                    Syntax
Key                                                                                                        EXTRACT [options] CAB_file [filenames]
       /B            When used in a batch script, this option will exit
                     only the script (or subroutine) but not CMD.EXE                                Key
                                                                                                          CAB_file     : Cabinet file
      exitCode          Sets the %ERRORLEVEL% to a numeric number.
                        If quitting CMD.EXE, set the process exit code no.                                filenames : Name of the file to extract from the cabinet
You should never attempt to directly write to the %errorlevel% variable, (i.e. don't try anything                     Wild cards (*.*) (.) and multiple files are valid
like SET errorlevel...) using the EXIT command provides a safe way to alter the value of the
built-in errorlevel variable.                                                                       options
Examples                                                                                                  /A              Process ALL cabinets. (where CABs are linked)
:: Exit if a required file is missing
@echo off                                                                                                    /C           If the CAB contains one file then /C will
If not exist MyimportantFile.txt Exit /b                                                                                  copy from DMF disks
Echo The file was found
:: Set the error level to 5                                                                                  /D           Display CAB directory
@echo off
call :setError                                                                                               /E           Extract all (use instead of *.* to extract all
                                                                                                    files)

Windows Command Prompt                                                         www.nubielab.com                                                                                                 Page 18
Powershell also has an Alias FC for the Format-Custom command, therefore to run the 'old' FC
      /L dir    Location to place extracted files (default is                                   under powershell you need to explicitly run C:windowssystem32fc.exe
current folder)
                                                                                                To identify 2 identical files use this syntax:
           /Y         Overwrite files without any prompt                                            FC file1.txt file2.txt | FIND "FC: no dif" > nul
                                                                                                    IF ERRORLEVEL 1 goto :s_files_are_different
FC.exe                                                                                          Example:
Compare the contents of two files or sets of files. Display any lines which do NOT match.
                                                                                                If two files are compared and the four lines of text match as follows
Syntax
       FC /B pathname1 pathname2
                                                                                                1: different
                                                                                                2: same
           FC [options] pathname1 pathname2
                                                                                                3: same
                                                                                                4: different
Key
      /B    : Perform a binary comparison.
                                                                                                Specifying /nnnn =2 the file compare will display the 4th line and continue
options                                                                                         Specifying /nnnn =3 the file compare will halt at the 4th line (files too different)
   /C : Do a case insensitive string comparison                                                 Specifying /LB1 the file compare will halt after the first line
                                                                                                FIND
   /A : Displays only first and last lines for each set of                                      Search for a text string in a file & display all the lines where it is found.
differences.                                                                                    Syntax
                                                                                                         FIND [/V] [/C] [/N] [/I] "string" [pathname(s)]
      /U    : Compare files as UNICODE text files.
      /L    : Compares files as ASCII text. (default)                                           key
                                                                                                      /V   : Display all lines NOT containing the specified string.
      /N    : Display line numbers (ASCII only)
                                                                                                      /C   : Count the number of lines containing the string.
   /LBn: Limit the number of lines that will be read, "n" sets a
maximum number                                                                                        /N   : Display Line numbers.
         of mismatches after which the File Comparison will
abort (resync failed)                                                                              /I : Ignore the case of characters when searching for the
         When FC aborts (resync failed) then "n" number of                                      string.
mismatches will be shown.
                                                                                                      "string"        : The text string to find (must be in quotes).
  /nnnn : Specify a number of consecutive lines that must match
after a mismatch.                                                                                     [pathname] : A drive, file or files to search.
           This can be used to prevent the display of the two                                   If a [pathname] is not specified, FIND will prompt for text input or will accept text piped from
files from getting                                                                              another command.
           too out of sync                                                                      (use CTRL-Z to end manual text input)

  /T        : Do not expand tabs to spaces.                                                     Examples:
  /W        : Compress white space (tabs and spaces) for
comparison.                                                                                     If names.txt contains the following:
To compare sets of files, use wildcards in pathname1 and pathname2 parameters.                      Joe Bloggs, 123 Main St, Dunoon
                                                                                                    Arnold Jones, 127 Scotland Street, Edinburgh

Windows Command Prompt                                                       www.nubielab.com                                                                                            Page 19
To search for "Jones" in names.txt                                                        /V       Print only lines that do NOT contain a match.
FIND "Jones" names.txt                                                                    /N       Print the line number before each line that matches.
                                                                                          /M       Print only the filename if a file contains a match.
---------- NAMES.TXT                                                                      /O       Print character offset before each matching line.
Arnold Jones, 127 Scotland Street, Edinburgh                                             /a color_attribute Display filenames in colour (2 hex digits)
If you want to pipe a command into FIND use this syntax                              When the search string contains multiple words (separated with spaces) then FINDSTR will
TYPE names.txt | FIND "Jones"                                                        show show lines that contains any one word - (an OR of each word) - this behaviour is reversed
You can also redirect like this                                                      if the string argument is prefixed with /C.
FIND /i "Jones" < names.txt >logfile.txt                                             Regular Expressions
                                                                                     (Searching for patterns of text)
To search a folder for files that contain a given search string
FOR %G IN (*.txt) do (find /n /i "SearchWord" "%G")                                  The FINDSTR syntax notation can use the following metacharacters which have special
                                                                                     meaning either as an operator or delimiter.
                                                                                      .              Wildcard: any character
FINDSTR                                                                               *              Repeat: zero or more occurances of previous character
Search for strings in files.                                                         or class
Syntax
         FINDSTR [options] [/F:file] [/C:string] [/G:file]                            ^              Line position: beginning of line
[string(s)] [pathname(s)]                                                             $              Line position: end of line
Key                                                                                   [class]        Character class: any one character in set
   string             Text to search for.                                             [^class]       Inverse class: any one character not in set
   pathname(s)        The file(s) to search.
   /C:string          Use string as a literal search string.                          [x-y]          Range: any characters within the specified range
   /G:file            Get search string from a file (/ stands for
console).                                                                             x             Escape: literal use of metacharacter x
   /F:file            Get a list of pathname(s) from a file (/ stands
for console).                                                                          <xyz         Word position: beginning of
   /d dirlist         Search a comma-delimited list of directories.                    xyz>         Word position: end of word
                                                                                     Metacharacters are most powerful when they are used together. For example, the combination of
options may be any combination of the following switches:                            the wildcard character (.) and repeat (*) character is similar in effect to the filename wildcard
                                                                                     (*.*)
      /I   Case-insensitive search.                                                  .*              Match any string of characters
      /S   Search subfolders.
                                                                                     The .* expression may be useful within a larger expression, for example f.*ing will match any
      /P   Skip any file that contains non-printable characters
                                                                                     string beginning with F and ending with ing.
      /L   Use search string(s) literally.
                                                                                     Examples:
      /R   Use search string(s) as regular expressions.(default)
                                                                                     Search for "granny" OR "Smith" in MyFile.txt.
      /B   Match pattern if at the Beginning of a line.
                                                                                     FINDSTR "granny Smith" MyFile.txt
      /E   Match pattern if at the END of a line.

      /X   Print lines that match exactly.                                           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 20
For example: to use the search criteria in Crit.txt to search the files listed in Files.txt and then
To search every file in the current folder and all subfolders for the word "Smith",                store the results in the file RESULTS.txt:
regardless of upper/lower case use:
                                                                                                   FINDSTR /g:Crit.txt /f:Files.txt> Results.txt
FINDSTR /s /i smith *.*                                                                            Errorlevel
                                                                                                   When an item is not found FINDSTR will return an errorlevel >0
Note that /S will only search below the current directory                                          Echo 12G6 |FindStr /R "[0-9]"
                                                                                                   If %ERRORLEVEL% EQU 0 echo The string contains one or more numeric characters
To find every line containing the word SMITH, preceeded by any number of spaces, and to            Echo 12G6 |FindStr /R "[^0-9]"
prefix each line found with a consecutive number:                                                  If %ERRORLEVEL% EQU 0 echo The string contains one or more non numeric characters
                                                                                                   Bugs
FINDSTR /b /n /c:" *smith" MyFile.txt                                                              In early versions of FindStr /F:file a path length of more than 80 chars will be truncated.

Finding a string only if surrounded by the standard delimiters
To find the word "computer", but not the words "supercomputer" or "computerise":                   FOR /F
                                                                                                   Loop command: against a set of files - conditionally perform a command against each item.
FINDSTR "<computer>" MyFile.txt                                                                  Syntax
                                                                                                            FOR /F ["options"] %%parameter IN (filenameset) DO
Now assume you want to find not only the word "computer", but also any other words that begin      command
with the letters comp, such as "computerise" or "compete"
                                                                                                           FOR /F ["options"] %%parameter IN ("Text string to
FINDSTR "<comp.*" MyFile.txt                                                                      process") DO command
Example of a literal search                                                                        Key
                                                                                                      options:
Searching a text file that contains the following                                                         delims=xxx             The delimiter character(s) (default = a
the quick brown fox                                                                                space)
the darkbrown fox
the really *brown* fox                                                                                   skip=n                  A number of lines to skip at the beginning of
FINDSTR /r .*brown MyFile.txt                                                                      the file.
or                                                                                                                                 (default = 0)
FINDSTR .*brown MyFile.txt
Will both match the word "brown" in all 3 lines                                                          eol=;        Character at the start of each line to
                                                                                                   indicate a comment
FINDSTR /L *brown* MyFile.txt                                                                                         The default is a semicolon ;
Will only match the last string
                                                                                                         tokens=n                Specifies which numbered items to read from
Using a script file                                                                                each line
                                                                                                                               (default = 1)
Multiple search criteria can be specified with a script file /G.
Multiple files to search can be specified with a source file /F.                                            usebackq             Specify `back quotes`:
                                                                                                                                 - Use double quotes to quote long file names
When preparing a source or script file, place each item on a new line.                             in filenameset.


Windows Command Prompt                                                          www.nubielab.com                                                                                                 Page 21
- Use single quotes for 'Text string to                                  You can use any character as a delimiter, but they are case sensitive.
process'                                                                                               If you don't specify delims it will default to "delims=<tab><space>"
                                 (useful if the text string contains double
quotes)                                                                                                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.
   Filenameset              A set of one or more files. Wildcards may be                               usebackq
used.                                                                                                  This option is useful when dealing with a filenameset that is a long filename containing spaces, it
                            If (filenameset) is a period character (.)                                 allows you to put double quotes around the filename.
then FOR will                                                                                          The backquote character ` is just below the ESC key on most keyboards.
                            loop through every file in the folder.                                     eol
                                                                                                       The default end-of-line character is a semicolon ';' when the FOR command reads a text file (or
    command                 The command to carry out, including any                                    even a character string), any line that STARTS with the eol character will be ignored. In other
                            command-line parameters.                                                   words it is treated as a comment.
                                                                                                       Use eol=X to change the eol character to X.
    %%parameter             A replaceable parameter:                                                   Most often you will want to turn this feature off so that every line of your data file is processed,
                            in a batch file use %%G (on the command line                               in theory "eol=" should turn this feature off, but in practice this fails to work correctly so instead
%G)                                                                                                    set eol to some unusual character that you don't expect to ever be in the data file e.g. "eol=€" or
FOR /F processing of a text file consists of reading the file, one line of text at a time and then     "eol=¬".
breaking the line up into individual items of data called 'tokens'. The DO command is then             Examples
executed with the parameter(s) set to the token(s) found.                                              Extracting data from this text file:
                                                                                                       January,Snowy,02
By default, /F breaks up the line at each blank space " ", and any blank lines are skipped, this       February,Rainy,15
default parsing behavior can be changed by applying one or more of the "options" parameters.           March,Sunny,25
The option(s) must be contained within "a pair of quotes"
Within a FOR loop the visibility of FOR variables is controlled via SETLOCAL                           FOR /F "tokens=1,3 delims=," %%G IN (weather.txt) DO @echo %%G %%H
EnableDelayedExpansion
                                                                                                       The tricky part is splitting up each the line into the right tokens, in this case I'm splitting on the
Tokens                                                                                                 comma character ',' this splits the line into 3 chunks of text and we pull out the first and third
tokens=2,4,6 will cause the second, fourth and sixth items on each line to be processed                items with "tokens=1,3"

tokens=2-6 will cause the second, third, fourth, fifth and sixth items on each line to be processed    token1 ,              token2 ,                 token3
                                                                                                       %%G                   <ignored>                %%H
tokens=* will cause all items on each line to be processed                                             January                                        02
tokens=3* will cause the 3rd and all subsequent items on each line to be processed                     February                                       15
                                                                                                       March                                          25
Each token specified will cause a corresponding parameter letter to be allocated.
                                                                                                       %%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
If the last character in the tokens= string is an asterisk, then additional parameters are allocated
                                                                                                       declare a parameter higher than the letter 'Z'.
for all the remaining text on the line.
                                                                                                       FOR parameter names are global, so in complex scripts which call one FOR statement from
Delims
                                                                                                       within another FOR statement you can refer to both sets of parameters. You cannot have more
More than one delimiter may be specified so a string like 'abcd+efg+hijk+lmno;pqr;stu+vwzyz'
                                                                                                       than 26 parameters active at any one time.
can be broken up using "delims=;+".


Windows Command Prompt                                                            www.nubielab.com                                                                                                   Page 22
Parse a text string:                                                                                                                       passed into the FOR parameter.
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).                                                command            : The command to carry out, including any
                                                                                                                                command-line parameters.
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                          %%parameter : A replaceable parameter:
paid %%G                                                                                                                 in a batch file use %%G (on the command line
Parse the output of a command:                                                                         %G)
FOR /F %%G IN ('"C:program Filescommand.exe"') DO ECHO %%G                                           FOR /F processing of a command consists of reading the output from the command one line at a
Parse the contents of a file:                                                                          time and then breaking the line up into individual items of data or 'tokens'. The DO command is
FOR /F "tokens=1,2* delims=," %%G IN (C:MyDocu~1mytex~1.txt) DO ECHO %%G                             then executed with the parameter(s) set to the token(s) found.
FOR /F "usebackq tokens=1,2* delims=," %%G IN ("C:My Documentsmy textfile.txt") DO
ECHO %%G                                                                                               The FOR command is the answer to innumerable questions where you want to take the output of
Filenameset                                                                                            some command, store it in a variable (%%G) then do something with the result.
To specify an exact set of files to be processed, such as all .MP3 files in a folder including         For example the PING command returns serveral lines including one like:
subfolders and sorted by date - just use the DIR /b command to create the list of filenames ~ and      Packets: Sent = 4, Recieved = 4, Lost = 0 (0% Loss),
use this variant of the FOR command syntax.                                                            To select that one line of output, you can search for the text "Loss" (which is always present),
FOR /F                                                                                                 then use the Tokens parameter to select the number of lost packets, here this is 0 but it will vary
Loop command: against the results of another command.                                                  each time you run the command.
Syntax                                                                                                 set _ping_cmd=ping -n 5 127.0.0.1
          FOR /F ["options"] %%parameter IN ('command_to_process')                                     FOR /f "tokens=4 delims=(=" %%G IN ('%_ping_cmd% ^|find "loss"') DO echo Result is
DO command                                                                                             [%%G]
                                                                                                       The tricky part is always splitting up the line of interest into the right tokens, in this case I'm
Key                                                                                                    splitting on the characters '=' and '('
      options:                                                                                         these two characters split the line into 5 chunks of text and we pull out the fourth one with
         delims=xxx           The delimiter character(s)                                               "tokens=4"
                              (default = a space)                                                      By default, /F breaks up the command output at each blank space, and any blank lines are
         skip=n               A number of lines to skip at the beginning.                              skipped.
                              (default = 0)                                                            You can override this default parsing behavior by specifying the "options" parameter. The
                                                                                                       options must be contained within "quotes"
      eol=;        Character at the start of each line to                                              usebackq
indicate a comment                                                                                     This option is useful when dealing with a command that already contains one or more straight
                   The default is a semicolon ;                                                        quotes.
                                                                                                       The backquote character ` is just below the ESC key on most keyboards. See the FOR /F page
         tokens=n             Specifies which numbered items to                                        for other effects of usebackq.
                              read from each line
                                    (default = 1)                                                      Tokens
                                                                                                       tokens=2,4,6 will cause the second, fourth and sixth items on each line to be processed
         usebackq             Specify `back quotes`
                                 the command_to_process is placed in `BACK                             tokens=2-6 will cause the second, third, fourth, fifth and sixth items on each line to be processed
quotes`
                                   instead of 'straight' quotes                                        tokens=* will cause all items on each line to be processed
      command_to_process : The output of the 'command_to_process'                                      tokens=3* will cause the 3rd and all subsequent items on each line to be processed
is

Windows Command Prompt                                                              www.nubielab.com                                                                                             Page 23
Although the above is a trivial example, being able to set %%G equal to each long filename in
Each token specified will cause a corresponding parameter letter to be allocated.                        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.
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
                                                                                                         FOR
                                                                                                         Conditionally perform a command several times.
More than one delimiter may be specified so a string like 'abcd+efg+hijk+lmno;pqr;stu+vwzyz'              syntax-FOR-Files
can be broken up using "delims=;+".                                                                               FOR %%parameter IN (set) DO command
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>"                                      syntax-FOR-Files-Rooted at Path
                                                                                                                FOR /R [[drive:]path] %%parameter IN (set) DO command
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.                                  syntax-FOR-Folders
eol                                                                                                             FOR /D %%parameter IN (folder_set) DO command
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           syntax-FOR-List of numbers
words it is treated as a comment.                                                                               FOR /L %%parameter IN (start,step,end) DO command
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,      syntax-FOR-File contents
in theory "eol=" should turn this feature off, but in practice this fails to work correctly so instead           FOR /F ["options"] %%parameter IN (filenameset) DO
set eol to some unusual character that you don't expect to ever be in the data file e.g. "eol=€" or      command
"eol=¬".
Examples:                                                                                                       FOR /F ["options"] %%parameter IN ("Text string to
                                                                                                         process") DO command
To ECHO from the command line, the name of every environment variable.
     FOR /F "delims==" %G IN ('SET') DO @Echo %G                                                           syntax-FOR-Command Results
The same command with usebackq (Windows 2000 and above)                                                             FOR /F ["options"] %%parameter IN ('command to process')
     FOR /F "usebackq delims==" %G IN (`SET`) DO @Echo %G                                                DO command
To put the Windows Version into an environment variable                                                  The operation of the FOR command can be summarised as...
     @echo off                                                                                                 Take a set of data
     ::parse the VER command                                                                                   Make a FOR Parameter %%G equal to some part of that data
     FOR /F "tokens=4*" %%G IN ('ver') DO SET _version=%%G                                                     Perform a command (optionally using the parameter as part of the command).
     :: show the result
                                                                                                               Repeat for each item of data
     echo %_version%
                                                                                                         If you are using the FOR command at the command line rather than in a batch program, specify
List all the text files in a folder                                                                      %parameter instead of %%parameter.
     FOR /F "tokens=*" %%G IN ('dir /b C:docs*.txt') DO echo %%G
                                                                                                         FOR Parameters
     FOR /F "tokens=*" %%G IN ('dir/b ^"c:program files*.txt^"')
                                                                                                         The first parameter has to be defined using a single character, I tend to use the letter G.
DO echo %%G
In the example above the long filename has to be surrounded in "quotes"
                                                                                                         e.g. FOR %%G IN ...
these quotes have to be escaped using ^
The "tokens=*" has been added to match all parts of any long filenames returned by the DIR
                                                                                                         In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value
command.


Windows Command Prompt                                                             www.nubielab.com                                                                                                    Page 24
If this results in a single value then %%G is set equal to that value and the command is           parameters in the final DO command.
performed.
                                                                                                   If Command Extensions are disabled, the FOR command will only support the basic syntax with
If this results in a multiple values then extra parameters are implicitly defined to hold each.    no enhanced variables:
These are automatically assigned in alphabetical order %%H %%I %%J ...(implicit parameter          FOR %%parameter IN (set) DO command [command-parameters]
definition)                                                                                        FORFILES.exe (Resource Kit)
Also if the parameter refers to a file, you can use an enhanced variable reference to quickly      Select a file (or set of files) and execute a command on each file. Batch processing.
extract the filename/path/date/size.                                                               Syntax
                                                                                                             FORFILES [/p Path] [/m Mask] [/s] [/c Command] [/d [+ | -]
Example                                                                                            {dd/MM/yyyy | dd}]
FOR /F "tokens=1-5" %%G IN ("This is a long sentence") DO @echo %%G %%H %%J
will result in the output                                                                          Key
This is long                                                                                             /p Path         The Path to search          (default=current folder)
You can of course pick any letter of the alphabet other than %%G.
                                                                                                         /s              Recurse into sub-folders
%%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            /C command      The command to execute for each file.
parameters.                                                                                                              Wrap the command string in double quotes.
G>H>I>J>K>L>M                                                                                                            Default = "cmd /c echo @file"

Using variables correctly                                                                                                The Command variables listed below can also be
Environment variables within a FOR loop are expanded at the beginning of the loop and won't        used in the
change until AFTER the end of the DO section.                                                                            command string.
The following example counts the files in the current folder, but %count% always returns 1:
@echo off                                                                                             /D date            Select files with a last modified date greater
SET count=1                                                                                        than or
 FOR /f "tokens=*" %%G IN ('dir /b') DO (                                                                                equal to (+), or less than or equal to (-),
 echo %count%:%%G                                                                                                        the specified date using the "dd/MM/yyyy"
 set /a count+=1)                                                                                  format;
To make this work correctly we must force the variable %count% to be evaluated during each                               or selects files with a last modified date
iteration, using the CALL :subroutine mechanism:                                                   greater than
@echo off                                                                                                                or equal to (+) the current date plus "dd" days,
SET count=1                                                                                        or
FOR /f "tokens=*" %%G IN ('dir /b') DO (call :s_do_sums "%%G")                                                           less than or equal to (-) the current date minus
                                                                                                   "dd" days.
GOTO :eof
                                                                                                                         A valid "dd" number of days can be any number in
:s_do_sums
                                                                                                                         the range of 0 - 32768.
 echo %count%:%1
                                                                                                                         "+" is taken as default sign if not specified.
 set /a count+=1
 GOTO :eof
                                                                                                         Command Variables:
Nested FOR commands
                                                                                                            @file    The name of the file.
                                                                                                            @fname   The file name without extension.
FOR commands can be nested FOR %%G... DO (for %%U... do ...)                                                @ext     Only the extension of the file.
when nesting commands choose a different letter for each part. you can then refer to both                   @path    Full path of the file.

Windows Command Prompt                                                         www.nubielab.com                                                                                       Page 25
@relpath Relative path of the file.                                                       /C               Compression - files added to the new disk
         @isdir          Returns "TRUE" if a file type is a directory,                          will be compressed.
                         and "FALSE" for files.
         @fsize          Size of the file in bytes.                                             [size] may be defined either with /F:size or /A:size
         @fdate          Last modified date of the file.
         @ftime          Last modified time of the file.                                           /F:size         size is the size of the floppy disk (720,
To include special characters in the command line, use the hex code for the character in 0xHH   1.2, 1.44, 2.88, or 20.8).
format (ex. 0x09 is theTAB character, 0x22 is the double quote " character.) so "C:Program
Files" becomes ^0x22C:Program^ Files^0x22                                                          /A:size               Allocation unit size.
Internal CMD.exe commands must be preceded with "cmd /c".                                                                   Default settings (via /F) are strongly
If ForFiles finds one or more matches if will return %errorlevel% =0                            recommended for general use.
If ForFiles finds no matches if will return %errorlevel% =1 and will print "ERROR: No files                                 NTFS supports 512, 1024, 2048, 4096, 8192,
found with the specified search criteria."                                                      16K, 32K, 64K.
Very early versions of ForFiles use unix style -parameters, can only match dates newer than a                               FAT supports 8192, 16K, 32K, 64K, 128K, 256K.
specified date and use the following command variables names: (which must be upper case)                                    NTFS compression is not supported for
@FILE, @FNAME_WITHOUT_EXT, @EXT, @PATH, @RELPATH, @ISDIR, @FSIZE,                               allocation units above 4096.
@FDATE, @FTIME                                                                                  Example
Examples:                                                                                       @echo off
Print a warning if the testfile is 5 days old or older:                                         Echo Warning this will reformat the entire D: disk!
C:> forfiles /m testfile.txt /c "cmd /c echo file is too old" /d -5                            PAUSE
                                                                                                format D: /FS:NTFS /x
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
                                                                                                FTYPE
                                                                                                Display or change the link between a FileType and an executable program
List the size of all .doc files:                                                                Syntax
C:> FORFILES /S /M *.doc /C "cmd /c echo @fsize"                                                   FTYPE fileType=executable_path

                                                                                                      FTYPE
FORMAT.com
Format a disk for use with Windows.                                                                   FTYPE fileType
Syntax
        FORMAT drive: [/FS:file-system] [/V:label] [/Q] [size]                                        FTYPE fileType=
[/C]
                                                                                                Key
Key                                                                                                   fileType             : The type of file
   /FS:file-system The file system (FAT or NTFS).
                   The NTFS file system does not function on                                         executable_path : The executable program including any
floppy disks.                                                                                   command line parameters
                                                                                                More than one file extension may be associated with the same File Type.
      /V:label              The volume label.                                                   e.g. both the extension .JPG and the extension .JPEG may be associated with the File Type
                                                                                                "jpegfile"
      /Q                    Quick format.
                                                                                                File Types can be displayed in the Windows Explorer GUI under Options, File Types however

Windows Command Prompt                                                       www.nubielab.com                                                                                         Page 26
the naming used is not consistent e.g. the File Type "txtfile" is displayed in the GUI as "Text    Switching a File Association between multiple applications
Document"and "jpegfile" is displayed as "image/jpeg"
                                                                                                   If you have multiple applications that use the same file extension, the ASSOC command can be
Several FileTypes can be linked to the same executable application.                                used to switch the file extension between the different FileTypes.

FTYPE filetype will display the current executable program for that file type e.g. FTYPE           Deleting a FileType
jpegfile.
                                                                                                   Specify executable_path=nothing and the FTYPE command will delete the executable_path
FTYPE without any parameters will display all FileTypes and the executable program for each.       for that FileType.
                                                                                                   For example:
Defining command line parameters                                                                   FTYPE htmlfile=

It is almost always necessary to supply command line parameters so that when a document is         Backup your FileTypes
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       FTYPE >backup_types.txt
back to the application.                                                                           ASSOC >backup_ext.txt

Command line parameters are exactly like batch file parameters, %0 is the executable program       Restore your FileTypes from a Backup
and %1 will reference the document filename
                                                                                                   FOR /F "tokens=* delims=" %G IN (backup_types.txt) DO FTYPE %G
so a simple command line might be:                                                                 FOR /F "tokens=* delims=" %G IN (backup_ext.txt) DO ASSOC %G

MyApplication.exe "%1"                                                                             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
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    Using File associations at the command line
nth parameter, use %~n where n is between 2 and 9.
                                                                                                   If you have a file association between .DOC and Word for Windows then at a command prompt
The FileType should always be created before making a File Association                             you can open a document with any of the following commands:

For example:                                                                                       Start "My Document.doc"
                                                                                                   "Monthly Report.doc"
FTYPE htmlfile="C:PROGRA~1Plus!MICROS~1iexplore.exe" -nohome                                   JULY.DOC
ASSOC .html=htmlfile

FTYPE pagemill.html=C:PROGRA~1AdobePAGEMI~1.0PageMill.exe "%1"
ASSOC .html=pagemill.html
                                                                                                   GOTO
                                                                                                   Direct a batch program to jump to a labelled line.
FTYPE rtffile="C:Program FilesWindows NTAccessoriesWORDPAD.EXE" "%1"                           Syntax
ASSOC .rtf=rtffile                                                                                          GOTO label

FTYPE word.rtf.8="C:Program FilesMicrosoft OfficeOfficewinword.exe" /n                         Key
ASSOC .rtf=word.rtf.8                                                                                 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 27
To exit a batch script file or exit a subroutine specify GOTO:eof this will transfer control to the              ICACLS FileName [/grant[:r] User:Permission[...]]
end of the current batch file, or the end of the current subroutine.                                                [/deny User:Permission[...]]
Examples:                                                                                                              [/remove[:g|:d]] User[...]]
                                                                                                                          [/t] [/c] [/l] [/q]
IF %1==12 GOTO MySubroutine                                                                                                  [/setintegritylevel Level[...]]
Echo the input was NOT 12
goto:eof                                                                                              Syntax (Store acls for all matching names into aclfile
                                                                                                               for later use with /restore)
:MySubroutine                                                                                               ICACLS name /save aclfile [/T] [/C] [/L] [/Q]
Echo the input was 12
goto:eof                                                                                              Syntax (restore folder)
                                                                                                            ICACLS directory [/substitute SidOld SidNew [...]]
Use a variable as a label                                                                                       /restore aclfile [/C] [/L] [/Q]

CHOICE /C:01 /m choose [Y]yes or [N]No                                                                Syntax (Change Owner)
goto s_routine_%ERRORLEVEL%                                                                                 ICACLS name /setowner user [/T] [/C] [/L] [/Q]

:s_routine_0                                                                                          Syntax (Find items with an ACL that mentions a specific SID)
Echo You typed Y for yes                                                                                    ICACLS name /findsid Sid [/T] [/C] [/L] [/Q]
goto:eof
                                                                                                      Syntax (Find files whose ACL is not in canonical form or
:s_routine_1                                                                                                   with a length inconsistent with the ACE count.)
Echo You typed N for no                                                                                     ICACLS name /verify [/T] [/C] [/L] [/Q]
goto:eof
                                                                                                      Syntax (Replace ACL with default inherited acls for all matching
                                                                                                      files)
Skip commands by using a variable as a :: comment (REM)
                                                                                                             ICACLS name /reset [/T] [/C] [/L] [/Q]
In this example the COPY command will only run if the parameter "Update" is supplied to the
                                                                                                      Key
batch
                                                                                                            /T   Traverse all subfolders to match files/directories.
@echo off
setlocal
                                                                                                         /C Continue on file errors (access denied)       Error messages
IF /I NOT %1==Update SET _skip=::
                                                                                                      are still displayed.
%_skip% COPY x:update.dat
                                                                                                         /L Perform the operation on a symbolic link itself, not its
%_skip% echo Update applied                                                                           target.
...
If Command Extensions are disabled GOTO will no longer recognise the :EOF label                             /Q   Quiet - supress success messages.
"GOTO... how bad can it be??..." - XKCD
iCACLS.exe (2003 sp2, Vista)                                                                                /grant :r user:permission
Change file and folder permissions - display or modify Access Control Lists (ACLs) for files and                Grant access rights, with :r, the permissions
folders.                                                                                                        will replace any previouly granted explicit permissions.
iCACLS resolves various issues that occur when using the older CACLS & XCACLS                                   Otherwise the permissions are added.
Syntax (files)

Windows Command Prompt                                                           www.nubielab.com                                                                      Page 28
/deny user:permission                                                                    GE - generic execute
       Explicitly deny the specified user access rights.                                    GA - generic all
       This will also remove any explicit grant of the                                      RD - read data/list directory
       same permissions to the same user.                                                   WD - write data/add file
                                                                                            AD - append data/add subdirectory
   /remove[:[g|d]] User                                                                     REA - read extended attributes
       Remove all occurrences of User from the acl.                                         WEA - write extended attributes
            :g remove all granted rights to that User/Sid.                                  X - execute/traverse
            :d remove all denied rights to that User/Sid.                                   DC - delete child
                                                                                            RA - read attributes
    /setintegritylevel [(CI)(OI)]Level                                                      WA - write attributes
       Add an integrity ACE to all matching files.                                  inheritance rights may precede either form and are
       level is one of L,M,H (Low Medium or High)                       applied
                                                                                    only to directories:
       A Directory Inheritance option for the integrity ACE may                                (OI) - object inherit
precede the level:                                                                             (CI) - container inherit
          /inheritance:e|d|r                                                                   (IO) - inherit only
             e - enable inheritance                                                            (NP) - don't propagate inherit
             d - disable inheritance and copy the ACEs                  Unlike many other command-line tools, iCACLS correctly preserves the canonical ordering of
             r - remove all inherited ACEs                              ACE entries:
                                                                        Explicit denials
   user   A user account, Group or a SID                                Explicit grants
                                                                        Inherited denials
   /restore   Apply the acls stored in ACLfile to the files in          Inherited grants
directory                                                               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
   permission is a permission mask and can be specified in one          normally inherits ACL's from the folder where it was created.
of two forms:
        a sequence of simple rights:                                    Using iCACLS
                F - full access                                              To edit a file you must already have the "Change" ACL (or be the file's owner)
                M - modify access                                            To use the iCACLS command to change the permissions of a file requires "FULL
                RX - read and execute access                                     Control" (or be the file's owner)
                R - read-only access
                                                                             File "Ownership" will always override all ACL's - you always have Full Control over
                W - write-only access
                                                                                 files that you create.
        a comma-separated list in parenthesis of specific
                                                                        Inherited folder permissions are displayed as:
rights:
                                                                          OI - Object inherit                 - This folder and files. (no inheritance
                D - delete
                                                                        to subfolders)
                RC - read control
                                                                          CI - Container inherit - This folder and subfolders.
                WDAC - write DAC
                                                                          IO - Inherit only                   - The ACE does not apply to the current
                WO - write owner
                                                                        file/directory
                S - synchronize
                AS - access system security
                                                                        These can also be combined as folllows:
                MA - maximum allowed
                                                                         (OI)(CI)          This folder, subfolders, and files.
                GR - generic read
                                                                         (OI)(CI)(IO) Subfolders and files only.
                GW - generic write
                                                                             (CI)(IO) Subfolders only.
Windows Command Prompt                               www.nubielab.com                                                                                             Page 29
(OI)        (IO) Files only.                                                                     String syntax
So BUILTINAdministrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F'         IF [/I] [NOT] item1==item2 command
(Fullcontrol)
similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)                 IF [/I] item1 compare-op item2 command
When cacls is applied to the current folder only there is no inheritance and so no output.
Bugs                                                                                                     IF [/I] item1 compare-op item2 (command) ELSE (command)
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       Error Check Syntax
returns “Access denied”.                                                                              IF [NOT] DEFINED variable command
A limited release hotfix is available to resolve this issue (Q947870) alternatively use
SUBINACL                                                                                                 IF [NOT] ERRORLEVEL number command
nb this bug is NOT present on Vista SP1 or Windows Server 2008.
Examples:                                                                                                IF CMDEXTVERSION number command

To backup the ACLs of every file in a directory type:                                              key
icacls * /save Myacl_backup.txt                                                                          item            May be a text string or an environment variable
Restore ACLS using a previously saved acl file:                                                                          a variable may be modified using either
icacls /restore Myacl_backup.txt                                                                                         Substring syntax or Search syntax
Change the Integrity Level (IL) of a file to High:
                                                                                                         command         The command to perform
icacls MyReport.doc /setintegritylevel H
                                                                                                         NOT             perform the command if the condition is false.
Grant the group FileAdmins Delete and Write DAC permissions to Sales_Folder:
icacls Sales_Folder /grant FileAdmins:(D,WDAC)                                                           ==              perform the command if the two strings are equal.
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)                   /I              Do a case Insensitive string comparison.
icacls * /grant accountName:(NP)(RX) /T
                                                                                                         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 >=

IF                                                                                                 and <
                                                                                                                           This 3 digit syntax is necessary because the >
Conditionally perform a command.                                                                                           symbols are recognised as redirection operators
File syntax
                                                                                                   IF ERRORLEVEL n statements should be read as IF Errorlevel >= number
   IF [NOT] EXIST filename command
                                                                                                   i.e.
                                                                                                   IF ERRORLEVEL 0 will return TRUE when the errorlevel is 64
    IF [NOT] EXIST filename (command) ELSE (command)
                                                                                                   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 30
IF %ERRORLEVEL% GTR 0 Echo An error was found                                                         IF EXIST filename (
IF %ERRORLEVEL% LSS 0 Echo An error was found                                                         del filename
                                                                                                      ) ELSE (
IF %ERRORLEVEL% EQU 0 Echo No error found                                                             echo The file was not 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                                  The IF statement does not use any great intelligence when evaluating Brackets, so for example
Note some errors are negative numbers.                                                                the command below will fail:
When working with errorlevels in a batch file it's a good idea to also use SETLOCAL so that the       IF EXIST MyFile.txt (ECHO Some(more)Potatoes)
%ERRORLEVEL% variable is reset each time the batch file runs.                                         This version will work:
IF EXIST filename will return true if the file exists (this is not case sensitive).                   IF EXIST MyFile.txt (ECHO Some[more]Potatoes)
                                                                                                      Testing Numeric values
Examples:                                                                                             Do not use brackets or quotes when comparing numeric values
IF EXIST C:install.log (echo complete) ELSE (echo failed)                                            e.g.
                                                                                                      IF (2) GEQ (15) echo "bigger"
IF DEFINED _department ECHO Got the department variable                                               or
                                                                                                      IF "2" GEQ "15" echo "bigger"
IF DEFINED _commission SET /A _salary=%_salary% + %_commission%                                       These will perform a character comparison and will always echo "bigger"
                                                                                                      however the command
IF CMDEXTVERSION 1 GOTO start_process                                                                 IF 2 GEQ 15 echo "bigger"
                                                                                                      Will perform a numeric comparison and works as expected - notice that this behaviour is exactly
IF %ERRORLEVEL% EQU 2 goto sub_problem2                                                               opposite to the SET /a command where quotes are required.
Does %1 exist?                                                                                        The examples here all use GEQ, but this applies equally to all the compare-op operators: EQU,
                                                                                                      NEQ, LSS, LEQ, GTR, GEQ
To test for the existence of a command line parameter - use empty brackets like this                  when comparing numbers as a string "026" > "26"
                                                                                                      Wildcards
IF [%1]==[] ECHO Value Missing                                                                        Wildcards are not supported by IF, so %COMPUTERNAME%==SS6* will not match SS64
or
IF [%1] EQU [] ECHO Value Missing                                                                     A workaround is to retrieve the substring and compare just those characters:
                                                                                                      SET _prefix=%COMPUTERNAME:~0,3%
In the case of a variable that may be NULL - a null variable will remove the variable definition      IF %_prefix%==SS6 GOTO they_matched
altogether, so testing for NULLs becomes easy:                                                        Pipes
                                                                                                      When piping commands, the expression is evaluated from left to right, so
IF NOT DEFINED _example ECHO Value Missing                                                            IF... | ... is equivalent to (IF ... ) | ...
                                                                                                      you can also use the explicit syntax IF (... | ...)
IF DEFINED will return true if the variable contains any value (even if the value is just a space)    ERRORLEVEL
Test the existence of files and folders                                                               To deliberately raise an ERRORLEVEL in a batch script use the EXIT /B command.
IF EXIST name - will detect the existence of a file or a folder - the script empty.cmd will show if   It is possible (though not a good idea) to create a string variable called %ERRORLEVEL% (user
the folder is empty or not.                                                                           variable)
                                                                                                      if present such a variable will prevent the real ERRORLEVEL (a system variable) from being
Brackets                                                                                              used by commands such as ECHO and IF.
                                                                                                      To test for the existence of a user variable use SET errorlevel, or IF DEFINED ERRORLEVEL
You can improve the readability of a batch script by writing a complex IF...ELSE command over         If Command Extensions are disabled IF will only support direct comparisons: IF ==, IF EXIST,
several lines using brackets                                                                          IF ERRORLEVEL
e.g.                                                                                                  also the system variable CMDEXTVERSION will be disabled.

Windows Command Prompt                                                          www.nubielab.com                                                                                            Page 31
> ipconfig /all                               ... Show detailed information
                                                                                                      > ipconfig /renew                             ... renew all adapters
                                                                                                      > ipconfig /renew EL*                         ... renew any connection that
                                                                                                  has its
IPCONFIG                                                                                                                                                  name starting with EL
Configure IP (internet protocol configuration)
                                                                                                      > ipconfig /release *Con*                     ... release all matching
Syntax
                                                                                                  connections,
                                                                                                                                                          eg. "Local Area Connection
   IPCONFIG /all                    Display full configuration information.
                                                                                                  1" or
                                                                                                                                                                "Local Area Connection
  IPCONFIG /release [adapter]
                                                                                                  2"
                        Release the IP address for the specified
adapter.
                                                                                                        > ipconfig /setclassid "Local Area Connection" TEST
                                                                                                                                     ... set the DHCP class ID for
  IPCONFIG /renew [adapter]
                                                                                                  the
                        Renew the IP address for the specified
                                                                                                                                                          named adapter to = TEST
adapter.

   IPCONFIG /flushdns               Purge the DNS Resolver cache.
                                                                                                  KILL (Resource kit)
                                                                                                  Remove a running process from memory.
                                                                                                  Syntax
  IPCONFIG /registerdns Refresh all DHCP leases and re-register                                          KILL [option] process_id
DNS names.                                                                                               KILL [option] task_name
                                                                                                         KILL [option] window_title
  IPCONFIG /displaydns              Display the contents of the DNS Resolver
Cache.                                                                                            Option
                                                                                                               -f         Force process kill
  IPCONFIG /showclassid adapter                                                                   Note: Kill -f basically just nukes the process from existence, potentially leaking a lot of memory
                        Display all the DHCP class IDs allowed                                    and losing any data that the process hadn't committed to disk yet. It is there for worst case
for adapter.                                                                                      scenarios - when you absolutely must end the process now, and don't care whether proper
                                                                                                  cleanup gets done or not.
   IPCONFIG /setclassid            adapter [classid]
                                   Modify the dhcp class id.
                                                                                                  In WindowsXP, KILL is replaced with the superior TASKKILL - Allowing you to specify a
If the Adapter name contains spaces, use quotes: "Adapter Name"                                   remote computer, different user account etc - for more details run TASKKILL /?
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.                                                                                  LOGOFF.exe (Resource Kit)
                                                                                                  Log a user off.
For Release and Renew, if no adapter name is specified, then the IP address leases for all        Syntax
adapters bound to TCP/IP will be released or renewed.                                                     LOGOFF [/f] [/n]

For Setclassid, if no ClassId is specified, then the ClassId is removed.                          Key
Examples:                                                                                            /f   Force running processes to close, but will ask for user
     > ipconfig                                     ... Show information.                         confirmation.

Windows Command Prompt                                                         www.nubielab.com                                                                                            Page 32
The user will not be asked to save unsaved data.                                         "recipient" is one or more recipient(s)
                                                                                                    If more than one recipient - separate with ';' these must not be
    /n      Force running processes to close without confirmation.                                  ambiguous in the default address book.
            The user will be prompted to save unsaved data.                                         Mapisend requires MAPI - i.e the MS Outlook client needs to be installed.
By default LOGOFF will ask for user confirmation and prompt to save unsaved data.                   Examples
Windows security log events                                                                         mapisend -u "MS Exchange Settings" -p MyPassword -r
Logon Event IDs 528 and 540 = successful logon                                                      billg@sun.com -s "Subject" -m "Test message text"
Logoff Event ID 538 = logoff
Logon and logoff events also specify a Logon Type code:                                             mapisend -u "MS Exchange Settings" -p MyPassword -r billg@hp.com
Logon Type 2 – Interactive - Log on at the local keyboard / screen (see the event description for   -s "Subject" -t c:MyMail.txt >> c:mail.log
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          MEM
was sent over the network in clear text.                                                            Display memory usage.
Logon Type 9 – NewCredentials - If you use RunAs /netonly and records the logon event with          Syntax
logon type 2.                                                                                               MEM
Logon Type 10 – RemoteInteractive - Terminal Services, Remote Desktop or Remote                             MEM /C
Assistance.                                                                                                 MEM /D
Logon Type 11 – CachedInteractive - mobile users not connected to the network connecting with               MEM /P
cached credentials.
                                                                                                    Key
                                                                                                          /P    List programs in memory
MAPISEND (Back Office/Exchange Resource kit)                                                                    with the memory address and size of each
Send email from the command line.
Syntax                                                                                                    /D    List Programs(as /P) and also Devices
       MAPISEND -u "profile" -p password
             -r recipient -s "subject" -m text message [options]                                          /C    List programs in conventional memory and
                                                                                                                list programs in upper memory
         MAPISEND -u "profile" -p password                                                          MEM will only display details about the current CMD shell environment, programs running in a
            -r recipient -s "subject" -t text_file [options]                                        separate shell (or WIN32 programs) will not be listed - so it won't tell you anything about total
                                                                                                    memory usage.
options
      -i      interactive login (prompts for profile and password)
      -c      cc: list                                                                              MD
      -f      File Attachment - path and file name(s)
                                                                                                    Make Directory - Creates a new folder.
      -v      generates verbose output (an 8 line summary of the
                                                                                                    Syntax
message)
                                                                                                           MD [drive:]path
"profile" is the profile name (user mailbox) of sender
                                                                                                    Key
"subject" is the subject line

Windows Command Prompt                                                        www.nubielab.com                                                                                              Page 33
The path can consist of any valid characters up to the
maximum path length available                                                                     MKDIR is a synonym for MD
You should avoid using the following characters in folder names - they are known to cause
problems

© ® " - & ' ^ ( ) and @
                                                                                                  MOVE
                                                                                                  Move a file from one folder to another
also many extended characters may not be recognised by older 16 bit windows applications.         Syntax
                                                                                                          MOVE [options] [Source] [Target]
The maximum length of a full pathname (folders and filename) under NTFS or FAT is 260
                                                                                                  Key
characters.
                                                                                                        source : The path and filename of the file(s) to move.
Folder names are not case sensitive, but only folder names longer than 8 characters will always
                                                                                                        target : The path and filename to move file(s) to.
retain their case, as typed.
                                                                                                        options:
For Example                                                                                                         /Y       Suppress confirmation prompt.
C:temp> MD MyFolder
Make several folders with one command                                                                              /-Y       Enable confirmation prompt.
C:temp> MD Alpha Beta Gamma
                                                                                                  Both Source and Target may be either a folder or a single file.
will create
                                                                                                  The source may include wildcards (but not the destination).
                                                                                                  Under Windows 2000 and above, the default action is to prompt on overwrites unless the
C:tempAlpha
                                                                                                  command is being executed from within a batch script.
C:tempBeta
                                                                                                  To force the overwriting of destination files use the COPYCMD environment variable:
C:tempGamma
                                                                                                  SET COPYCMD=/Y
                                                                                                  Using the COPYCMD variable has the advantage that the command will still work in early
Make an entire path
                                                                                                  versions of windows (e.g. NT4) which don't support the /Y option (they overwrite by default).
MD creates any intermediate directories in the path, if needed.
                                                                                                  Examples:
For example, assuming utils does not exist then:
MD utilsdownloadsEditor
                                                                                                  In the current folder
    is the same as:
                                                                                                  MOVE oldfile.wp newfile.doc
    md   utils
    cd   utils                                                                                   Full path specified
    md   downloads                                                                                MOVE g:departmentoldfile.wp "c:Files to Convertnewfile.doc"
    cd   downloads
    md   Editor                                                                                   Specify the drive and filename (assumes the current folder on both drives is correct)
                                                                                                  MOVE a:oldfile.wp c:newfile.doc
for long filenames include quotes
                                                                                                  Specify source only (will copy the file to current folder, keeping the same filename)
MD "utilsdownloadsSuper New Editor"                                                            MOVE g:departmentoldfile.wp
You cannot create a folder with the same name as any of the following devices:
CON, PRN, LPT1, LPT2 ..LPT9, COM1, COM2 ..COM9                                                    Quiet move (no feedback on screen)
This limitation ensures that redirection to these devices will always work.                       MOVE oldfile.wp newfile.doc >nul

If you plan to copy data onto CDROM avoid folder trees more than 8 folders deep
Windows Command Prompt                                                        www.nubielab.com                                                                                            Page 34
allows in-use files to be replaced
MSG.exe
Send a pop-up message to a user. The 'Home' editions of Windows don’t include MSG.              /x : Prevents the default action that will otherwise create a
Syntax                                                                                                  folder called "deleted" containing a copy of the
        MSG username [options] [message]                                                                original file.
                                                                                            Note that you must use a FULL pathname to each file.
           MSG sessionname [options] [message]
                                                                                            The NT resource kit contains 2 versions of MV.EXE - a posix version and a Windows NT
           MSG sessionid      [options] [message]                                           version - they are not the same!

           MSG   @filename [options] [message]                                              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)
           MSG * [options] [message]
                                                                                            Start the registry editor (regedt32.exe not regedit.exe)
Options
                                                                                            Move to HKLMSYSTEMCurrentControlSetControlSession Manager
   /SERVER:servername           The server to contact (default is
current).                                                                                   Double click on
                                                                                            PendingFileRenameOperations
   /TIME:seconds                Time delay to wait for receiver to                          (if it does not exist - create of type multi_str )
acknowledge msg.
                                                                                            On the first line is the name of the new file with ?? in front,
      /V                        Verbose, display extra information.                         e.g.
                                                                                            ??d:tempntfs.sys
      /W                        Wait for response from user, useful with
/V.                                                                                         On the second line is the file to replaced with !?? in front,
                                                                                            e.g.
If no message text to send is specified, MSG will prompt for it                             !??c:winntsystem32driversntfs.sys
(also reads from stdin)
                                                                                            Click OK
@filename identifies a file containing a list of usernames,                                 So the complete Multi-String Data would appear like:
sessionnames or sessionids to send the message to.
                                                                                            ??d:tempntfs.sys
 * will send the message to all sessions on the server.                                     !??c:winntsystem32driversntfs.sys
   e.g. use this for Terminal Server/Citrix shutdown messages.
MV.exe (Resource Kit)                                                                       Once the reboot is complete and the file replaced the PendingFileRenameOperations value will
Move File - Copy a file to another location even if the file is in use (Locked)             be deleted from the registry
Syntax
        MV /x /d source destination

Key                                                                                         NETSH (Network Shell)
      The first file name is the file to be copied and the second                           Configure Network Interfaces, Windows Firewall, Routing & remote access.
      the destination pathname.                                                             Syntax
                                                                                                    NETSH [Context] [sub-Context] command
      /d : does not copy the file until reboot time

Windows Command Prompt                                                   www.nubielab.com                                                                                              Page 35
Key
The contexts and commands available vary by platform, the list             netsh advfirewall monitor delete           - Delete all matching
below is for Windows 2008.                                                 security associations.
Use interactive mode/help (described below) to check the                   netsh advfirewall monitor dump             - Display a
commands available on your machine.                                        configuration script.
                                                                           netsh advfirewall monitor show             - Show all matching
= add              - Add a configuration entry to a list of                security associations.
entries.
netsh add helper   - Install the specified helper DLL                      netsh advfirewall reset     - Reset to factory settings
                                                                           (Firewall=ON)
= advfirewall      - Change the 'netsh advfirewall' context.
                                                                           netsh advfirewall   set allprofiles     - Set properties in all
netsh advfirewall consec ?                - Display a list of              profiles.
commands.                                                                  netsh advfirewall   set currentprofile - Set properties in the
netsh advfirewall consec add              - Add a new connection           active profile.
security rule.                                                             netsh advfirewall   set domainprofile   - Set properties in the
netsh advfirewall consec delete           - Delete all matching            domain profile.
connection security rules.                                                 netsh advfirewall   set global          - Set the global
netsh advfirewall consec dump             - Display a                      properties.
configuration script.                                                      netsh advfirewall   set privateprofile - Set properties in the
netsh advfirewall consec set              - Set new values for             private profile.
properties of an existing rule.                                            netsh advfirewall   set publicprofile   - Set properties in the
netsh advfirewall consec show             - Display a specified            public profile.
connection security rule.
                                                                           netsh advfirewall show allprofiles       - Display properties for
netsh advfirewall dump     Create a script that contains the               all profiles.
current configuration.                                                     netsh advfirewall show currentprofile    - Display properties for
                          If saved to a file, this can be used             the active profile.
to restore the configuration settings.                                     netsh advfirewall show domainprofile     - Display properties for
                                                                           the domain properties.
netsh advfirewall export pathfilename    - Export the current             netsh advfirewall show global            - Display the global
policy to the specified file.                                              properties.
netsh advfirewall import pathfilename    - Import policy from the         netsh advfirewall show privateprofile    - Display properties for
specified file.                                                            the private profile.
                                                                           netsh advfirewall show publicprofile     - Display properties for
netsh advfirewall firewall add            - Add a new inbound or           the public profile.
outbound firewall rule.                                                    netsh advfirewall show store             - Display the policy store
netsh advfirewall firewall delete         - Delete all matching            for the current interactive session.
inbound rules.
netsh advfirewall firewall dump           - Display a                      =bridge          - Change to the 'netsh bridge' context.
configuration script.                                                      netsh bridge dump            - Display a configuration script.
netsh advfirewall firewall set            - Set new values for             netsh bridge install         - Install the component
properties of a existing rule.                                             corresponding to the current context.
netsh advfirewall firewall show           - Display a specified            netsh bridge set             - Set configuration information.
firewall rule.                                                             netsh bridge show            - Display information.

Windows Command Prompt                                  www.nubielab.com                                                                   Page 36
netsh bridge uninstall       - Remove the component corresponding       netsh firewall set opmode         - Set firewall operational
to the current context.                                                 configuration.
                                                                        netsh firewall set portopening    - Set firewall port
=delete         - Delete a configuration entry from a list of           configuration.
entries.                                                                netsh firewall set service        - Set firewall service
netsh delete helper   Remove the specified helper DLL from              configuration.
netsh.                                                                  netsh firewall show allowedprogram - Show firewall allowed
Note that after a helper is removed, it is no longer supported          program configuration.
by netsh.                                                               netsh firewall show config         - Show firewall
                                                                        configuration.
=dhcpclient     - Change to the 'netsh dhcpclient' context.             netsh firewall show currentprofile - Show current firewall
netsh dhcpclient list            - List all the commands                profile.
available.                                                              netsh firewall show icmpsetting    - Show firewall ICMP
netsh dhcpclient trace enable    - Enable tracing for DHCP              configuration.
client and DHCP QEC.                                                    netsh firewall show logging        - Show firewall logging
netsh dhcpclient trace disable   - Disable tracing for DHCP             configuration.
client and DHCP QEC.                                                    netsh firewall show multicastbroadcastresponse - Show firewall
                                                                        multicast/broadcast response configuration.
=dump           - Display a configuration script.                       netsh firewall show notifications - Show firewall notification
netsh dump   - Create a script that contains the current                configuration.
configuration.                                                          netsh firewall show opmode         - Show firewall operational
               If saved to a file, this can be used to restore          configuration.
the configuration settings.                                             netsh firewall show portopening    - Show firewall port
                                                                        configuration.
=exec            - Run a script file.                                   netsh firewall show service        - Show firewall service
exec    - Load a script file and run it.                                configuration.
                                                                        netsh firewall show state          - Show current firewall
=firewall       - Change to the 'netsh firewall' context.               state.
netsh firewall add                - Add firewall configuration.
netsh firewall delete             - Delete firewall                     =help                - Display a list of netsh commands.
configuration.                                                          netsh help
netsh firewall dump               - Display a configuration
script.                                                                 =http                - Change to the 'netsh http' context.
netsh firewall reset              - Reset firewall configuration        netsh http   add               - Add a configuration entry to a
to default.                                                             table.
netsh firewall set allowedprogram - Set firewall allowed program        netsh http   delete            - Delete a configuration entry from a
configuration.                                                          table.
netsh firewall set icmpsetting    - Set firewall ICMP                   netsh http   dump              - Display a configuration script.
configuration.                                                          netsh http   flush             - Flushe internal data.
netsh firewall set logging        - Set firewall logging                netsh http   show              - Display information.
configuration.
netsh firewall set multicastbroadcastresponse - Set firewall            =interface      - Change to the 'netsh interface' context.
multicast/broadcast response configuration.                             netsh interface 6to4           + Change to the 'netsh interface
netsh firewall set notifications - Set firewall notification            6to4' context.
configuration.

Windows Command Prompt                               www.nubielab.com                                                                     Page 37
netsh interface add            - Add a configuration entry to a          netsh ipsec static importpolicy          - Import the policies from a
table.                                                                   file to the policy store.
netsh interface delete         - Delete a configuration entry            netsh ipsec static set                   - Modify existing policies and
from a table.                                                            related information.
netsh interface dump           - Display a configuration script.         netsh ipsec static show                  - Display details of policies
netsh interface ipv4           + Change to the 'netsh interface          and related information.
ipv4' context.
netsh interface ipv6           + Change to the 'netsh interface          =lan                 - Change to the 'netsh lan' context.
ipv6' context.                                                           netsh lan   add               - Add a configuration entry to a table.
netsh interface isatap         + Change to the 'netsh interface          netsh lan   delete            - Delete a configuration entry from a
isatap' context.                                                         table.
netsh interface portproxy      + Change to the 'netsh interface          netsh lan   dump              -   Display a configuration script.
portproxy' context.                                                      netsh lan   export            -   Save LAN profiles to XML files.
netsh interface reset          -   Reset information.                    netsh lan   reconnect         -   Reconnect on an interface.
netsh interface set            -   Set configuration information.        netsh lan   set               -   Configure settings on interfaces.
netsh interface show           -   Display information.                  netsh lan   show              -   Display information.
netsh interface tcp            +   Change to the 'netsh interface
tcp' context.                                                            =nap             - Change to the 'netsh nap' context.
netsh interface teredo         + Change to the 'netsh interface          netsh nap client          + Change to the 'netsh nap client'
teredo' context.                                                         context.
                                                                         netsh nap dump            - Display a configuration script.
The following sub-contexts are available:                                netsh nap hra             + Change to the 'netsh nap hra'
      6to4 ipv4 ipv6 isatap portproxy tcp teredo                         context.
                                                                         netsh nap reset           - Reset configuration.
=ipsec           - Change to the 'netsh ipsec' context.                  netsh nap show            - Show configuration and state
netsh ipsec dump            - Display a configuration script.            information.
netsh ipsec dynamic add             - Add policy, filter, and
actions to SPD.                                                          =netio               - Change to the 'netsh netio' context.
netsh ipsec dynamic delete          - Delete policy, filter, and         netsh netio   add               - Add a configuration entry to a
actions from SPD.                                                        table.
netsh ipsec dynamic dump            - Display a configuration            netsh netio   delete              - Delete a configuration entry from a
script.                                                                  table.
netsh ipsec dynamic set             - Modifiy policy, filter, and        netsh netio   dump                - Display a configuration script.
actions in SPD.                                                          netsh netio   show                - Display information.
netsh ipsec dynamic show            - Display policy, filter, and
actions from SPD.                                                        =ras             - Change    to the 'netsh ras' context. (Remote
netsh ipsec static add             - Create new policies and             Access Server)
related information.                                                     netsh ras aaaa                - Change to the 'netsh ras aaaa'
netsh ipsec static delete          - Delete policies and related         context.
information.                                                             netsh ras add                 - Add items to a table.
netsh ipsec static dump            - Display a configuration             netsh ras delete              - Remove items from a table.
script.                                                                  netsh ras diagnostics         - Change to the 'netsh ras diagnostics'
netsh ipsec static exportpolicy    - Export all the policies from        context.
the policy store.                                                        netsh ras dump                - Display a configuration script.
                                                                         netsh ras ip                  - Change to the 'netsh ras ip' context.

Windows Command Prompt                                www.nubielab.com                                                                    Page 38
netsh ras ipv6             - Change to the 'netsh ras ipv6'               netsh winsock show                        - Display information.
context.
netsh ras set              - Set configuration information.               netsh                                          - Interactive mode
netsh ras show             - Display information.                         In interactive mode, switch context by typing any context name: advfirewall, bridge, firewall,
                                                                          http, interface, ipsec.. etc
=rpc             - Change to the 'netsh rpc' context. (RPC                list commands with ? exit interactive mode with Quit or Exit.
firewall filter)                                                          To view help for any command, type the command, followed by a space and ?
netsh rpc add             - Create an Add list of subnets.                The syntax on this page is based on Windows 2008, for backwards compatibility with XP dns is
netsh rpc delete          - Create a Delete list of subnets.              an alias for dnsserver, ip is an alias for ipv4
netsh rpc dump            - Display a configuration script.               Examples:
netsh rpc filter          - Change to the 'netsh rpc filter'              Install ipmontr.dll:
context.                                                                  C:> netsh advfirewall net add helper ipmontr.dll
netsh rpc reset           - Reset the selective binding settings
to 'none' (listen on all interfaces).                                     Export the fiewall policy:
netsh rpc show            - Display the selective binding state           C:> netsh advfirewall export "c:advfirewallpolicy.wfw"
for each subnet on the system.
                                                                          Show TCP/IP settings
=set            - Update configuration settings on a remote               C:> netsh interface ip show config
machine.
netsh set machine [name=] [user=][[DomainName]UserName]                  Set a static IP address (e.g. for a laptop)
[pwd=][Password | *]                                                      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
If a machine name is not specified, the local machine is used.
A username and password cannot be used to connect to the local            Set a dynamic IP address with DHCP
machine.                                                                  C:> Netsh interface ip set address name="Local Area Connection" source=dhcp
=show            - Display information.                                   Add multiple DNS servers:
netsh show alias    - List all defined aliases.                           C:> Netsh interface ipv4 add dns "Local Area Connection" 10.0.0.1
netsh show helper - List all the top-level helpers.                       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.
=winhttp           - Change to the 'netsh winhttp' context.
netsh winhttp    dump           - Display a configuration script.
                                                                          Set a static DNS server address:
netsh winhttp    import         - Import WinHTTP proxy settings.
                                                                          C:> Netsh interface ip set dns name="Local Area Connection" source=static addr=192.168.0.2
netsh winhttp    reset          - Reset WinHTTP settings.
                                                                          register=none
netsh winhttp    set            - Configure WinHTTP settings.
netsh winhttp    show           - Display currents settings.
                                                                          Set a dynamic DNS server address with DHCP:
                                                                          C:> netsh interface ip set dns name="Local Area Connection" source=dhcp
=winsock        - Change to the 'netsh winsock' context.
netsh winsock audit          - Display a list of Winsock LSPs
that have been installed and removed.                                     Set a static address for the WINS server:
netsh winsock dump           - Display a configuration script.            C:> Netsh interface ip set wins name="Local Area Connection" source=static
netsh winsock remove         - Remove a Winsock LSP from the              addr=192.168.100.3
system.
netsh winsock reset          - Reset the Winsock Catalog to a             To configure WINS from DHCP:
clean state.                                                              C:> Netsh interface ip set wins name="Local Area Connection" source=dhcp

Windows Command Prompt                                 www.nubielab.com                                                                                         Page 39
-S   (Sessions)                  List sessions table with the destination
Backup the local DHCP server configuration to a file:                                          IP addresses
C:> netsh dump dhcp > C:backupDHCPconfig.dat                                                   -s   (sessions)                  List sessions table converting
You can use this backup file to recreate the DHCP server with Netsh .                          destination IP
                                                                                                                      addresses to computer NETBIOS names.
Work against a remote machine:                                                                   -RR (ReleaseRefresh) Send Name Release packets to WINS and
C:> netsh set machine server64                                                                then, starts Refresh

Backup the current network interface configuration to a file:                                    interval                         Redisplay selected statistics, pausing
C:> netsh dump interface > c:backupInterfaceConfig.dat                                       interval seconds
                                                                                                                                  between each display. Press Ctrl+C to
Restore network interface configuration from a file:                                           stop redisplaying
C:> netsh exec c:backupInterfaceConfig.dat                                                                                      statistics.
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                                       NETSTAT.exe
NBTSTAT.exe                                                                                    Display current TCP/IP network connections and protocol statistics.
Display protocol statistics and current TCP/IP connections using NBT (NetBIOS over TCP/IP).    Syntax
Syntax                                                                                             NETSTAT [options] [-p protocol] [interval]
      By Name
         NBTSTAT -a Remote_host_Name [options] [interval]                                      Key
                                                                                                  -a   Display        All connections and listening ports.
    By IP address                                                                                 -e   Display        Ethernet statistics. (may be combined with -s)
       NBTSTAT -A IP_address [options] [interval]                                                 -n   Display        addresses and port numbers in Numerical form.
                                                                                                  -r   Display        the Routing table.
Key                                                                                               -o   Display        the Owning process ID associated with each
  -a   (adapter status) List the remote machine's name table                                   connection.
given its name
  -A   (Adapter status) List the remote machine's name table                                      -b   Display the exe involved in creating each connection or
given its IP address                                                                           listening port.*
  -c   (cache)          List NBT's cache of remote [machine]                                      -v   Verbose - use in conjunction with -b, to display the
names                                                                                          sequence of
                        and their IP addresses                                                         components involved for all executables.
  -n   (names)          List local NetBIOS names.
  -r   (resolved)       List names resolved by broadcast and via                                     -p protocol
WINS                                                                                                      Show only connections for the protocol specified;
  -R   (Reload)         Purge and reloads the remote cache name                                           may be any of: TCP, UDP, TCPv6 or UDPv6.
table                                                                                                     If used with the -s option then the following protocols

Windows Command Prompt                                                     www.nubielab.com                                                                          Page 40
may also be specified: IP, IPv6, ICMP,or ICMPv6.
                                                                                                   set all            - print options, current server and host
      -s      Display per-protocol statistics.               By default, statistics                finger [USER]      - finger the optional NAME at the current
are                                                                                               default host
              shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and                               MyHost             - print ip address of MyHost
UDPv6;                                                                                             MyHost MyNameServer - print ip address of MyHost on
              (The v6 protocols are not available under 2k and NT4)                               MyNameServer
              The -p option may be used to display just a subset of                                set [no]debug      - print debugging info
these.                                                                                             set [no]d2         - print exhaustive debugging info

   interval            Redisplay statistics, pausing interval seconds                              set domain=NAME    - set default domain name to NAME
between                                                                                            set root=NAME      - set root server to NAME
                        each display. (default=once only) Press CTRL+C                             root               - set current default server to the root
to stop.                                                                                           server NAME        - set default server to NAME, using current
* Where available this will display the sequence of components involved in creating the           default server
connection or listening port. (Typically well-known executables which host multiple independent    lserver NAME       - set default server to NAME, using initial
components.) This option will display the executable name in [ ] at the bottom, with the          server
component it called on top, repeated until TCP/IP is reached. The -b option can be time-           set srchlist=N1[/N2/.../N6] - set domain to N1 and search list
consuming and will fail unless you have sufficient permissions.                                   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
NSLOOKUP (TCP/IP)                                                                                  set class=X            -   set query class (for example, IN
Lookup IP addresses on a NameServer.                                                              (Internet), ANY)
Syntax                                                                                             set [no]msxfr          - use MS fast zone transfer
  Lookup the ip address of MyHost:                                                                 set ixfrver=X          - current version to use in IXFR transfer
                                                                                                  request
           NSLOOKUP [-option] MyHost                                                               set type=X             - set query type
                                                                                                   set querytype=X        - set query type
  Lookup ip address of MyHost on MyNameServer:                                                                              (e.g. A, ANY, CNAME, MX, NS, PTR, SOA,
                                                                                                  SRV)
           NSLOOKUP [-option] MyHost MyNameServer
                                                                                                   ls [opt] DOMAIN [> FILE] - list addresses in DOMAIN
  Enter "command mode":                                                                                                       (and optionally output to FILE)

           NSLOOKUP                                                                                   -d             -   list all records
                                                                                                      -t TYPE        -   list records of the given Type (for example,
Command Mode options:                                                                             A, CNAME,
                                                                                                                         MX, NS, PTR, and so on)
 help or ?                   - print a list of Command Mode options                                      -a          -   list Aliases and canonical names.
 exit or ^C                  - exit "command mode"

Windows Command Prompt                                                      www.nubielab.com                                                                      Page 41
view FILE              - sort an 'ls' output file and view it with pg                Generate security audits                          SeAuditPrivilege
Example:                                                                              Manage auditing and security log SeSecurityPrivilege
C:> nslookup -querytype=TXT -timeout=10 porttest.dns-oarc.net                        Backup files and directories                      SeBackupPrivilege
                                                                                      Add workstations to the domain                    SeMachineAccountPrivilege
                                                                                      Shut down the system                              SeShutdownPrivilege
NTRIGHTS.exe (Resource Kit, 2000/2003)                                                Force shutdown from a remote system SeRemoteShutdownPrivilege
Edit user account Privileges.                                                         Create a pagefile                                 SeCreatePagefilePrivilege
Syntax                                                                                Increase quotas                                   SeIncreaseQuotaPrivilege
           NTRIGHTS +r Right -u UserOrGroup [-m Computer] [-e                       Restore files and directories                     SeRestorePrivilege
Entry]                                                                                Change the system time                            SeSystemTimePrivilege
                                                                                      Manage the files on a volume                      SeManageVolumePrivilege (Win
         NTRIGHTS -r Right -u UserOrGroup [-m Computer] [-e                       XP only)
Entry]                                                                                Take ownership of files/objects SeTakeOwnershipPrivilege
                                                                                      Enable computer/user accounts
Key:                                                                                     to be trusted for delegation
                                                                                    SeEnableDelegationPrivilege
   +/-r Right             Grant or revoke one of the rights listed                    Remove computer from docking station SeUndockPrivilege
below.                                                                              Service Privileges:
                                                                                      Create permanent shared objects SeCreatePermanentPrivilege
       -u UserOrGroup     Who the rights are to be granted or revoked                 Create a token object                             SeCreateTokenPrivilege
to.                                                                                   Replace a process-level token                     SeAssignPrimaryTokenPrivilege
                                                                                      Impersonate a client after authentication
     -m Computer        The computer (machine) on which to perform                SeImpersonatePrivilege (Not supported on WinXP or earlier)
the operation.                                                                        Increase scheduling priority
                          The default is the local computer.                        SeIncreaseBasePriorityPrivilege
                                                                                      Act as part of the operating system                      SeTcbPrivilege
       -e Entry                 Add a text string 'Entry' to the computer's           Profile a single process
event log.                                                                          SeProfileSingleProcessPrivilege
Below are the Privileges that can be granted or revoked, all are Case-Sensitive.      Load and unload device drivers                    SeLoadDriverPrivilege
Logon Privileges:                                                                     Lock pages in memory                              SeLockMemoryPrivilege
 Log on as a batch job                             SeBatchLogonRight                  Create global objects                             SeCreateGlobalPrivilege (Not
 Deny logon as a batch job                   SeDenyBatchLogonRight                  supported on Windows XP or earlier)
 Log on locally                                    SeInteractiveLogonRight          Misc Privileges:
 Deny local logon                            SeDenyInteractiveLogonRight              Debug programs                                    SeDebugPrivilege
 Logon as a service                                SeServiceLogonRight                Bypass traverse checking                          SeChangeNotifyPrivilege
 Deny logon as a service                     SeDenyServiceLogonRight                  Synch directory service data                      SeSyncAgentPrivilege
 Access this Computer from the Network                                                Edit firmware environment values SeSystemEnvironmentPrivilege
SeNetworkLogonRight                                                                   Profile system performance                        SeSystemProfilePrivilege
 Deny Access to this computer from the network                                        Obsolete and unused                               SeUnsolicitedInputPrivilege
SeDenyNetworkLogonRight                                                             (has no effect)
 Allow logon through Terminal Services                                              To run ntrights you need to be an administrator, to change privileges remotely (-m option) you
SeRemoteInteractiveLogonRight (Not supported on Win 2000)                           need to have administrator rights on the machine being changed.
 Deny logon through Terminal Services                                               To change permissions for a large number of users, add them to a domain workgroup and grant
SeDenyRemoteInteractiveLogonRight (Not supported on Win 2000)                       the privileges to the group.
System Admin Privileges:                                                            The group policy editor can be used to view these privileges in a GUI.

Windows Command Prompt                                           www.nubielab.com                                                                                          Page 42
On a Windows 2008 Server (or Vista), allowing logon through Terminal Services                          /nh    No column headers in the output. Valid only when /fo =
(SeRemoteInteractiveLogonRight) requires an extra step: Control Panel > System > 'Remote            TABLE or CSV.
Settings' > 'Select Users' button, and then add users/groups.
Examples:                                                                                              /id    Disconnect the file opened with the specified numeric
Allow all members of the local 'Users' group to logon locally                                       OpenFileID on computer
ntrights -u Users +r SeInteractiveLogonRight                                                                  Use openfiles.exe /query to learn the file ID.
Allow all members of the 'Admin_RDP' group to logon remotely via RDP to "server64", also log                  The wildcard (*) can be used to disconnect all open
this security change in the event log:                                                              files on computer.
ntrights -u MyDomAdmin_RDP +r SeRemoteInteractiveLogonRight -m server64 -e "Added
RDP rights for Admin_RDP"                                                                              /a     Disconnect all open files that were accessed by user
Allow all members of the domain group 'Admin_General' to shutdown this computer.                    on computer.
                                                                                                              The wildcard (*) can be used to disconnect all open
ntrights -u MyDomAdmin_General +r SeShutdownPrivilege
                                                                                                    files on computer.
Allow the domain user 'JDoe' to shutdown the machine 'Server64'
ntrights -u MyDomJDoe +r SeShutdownPrivilege -m Server64
                                                                                                       /o     Disconnect all open files with the specified OpenMode
Specifically deny local logon rights to Henry:                                                      on the computer specified by the /s parameter.
ntrights -u Henry +r SeDenyInteractiveLogonRight                                                              The OpenMode parameter includes the Read/Write and
"What distinguishes the majority of men from the few is their inability to act according to their   Read modes.
beliefs." - Henry Miller                                                                                      The wildcard (*) can be used to disconnect all open
                                                                                                    files on computer.

OPENFILES.exe                                                                                          /se    Disconnect all open files that were created by the
                                                                                                    specified session on computer.
Query or display open files, disconnect files opened by network users.
Syntax                                                                                                        Wildcards (*) may be used. (the /se option is not
        Openfiles.exe /query [/s Computer [/u DomainUser [/p                                       available under Windows 7)
Password]]]
           [/fo {TABLE|LIST|CSV}] [/nh] [/v]                                                           /op    Disconnect the open file that was created with the
                                                                                                    specified OpenFileName on computer
      Openfiles.exe /disconnect [/s Computer [/u DomainUser                                                  The wildcard (*) can be used to disconnect all open
[/p Password]]]                                                                                     files on computer.
         {[/id OpenFileID]|[/a UserName]|[/o OpenMode]} [/se
SessionName] [/op OpenFileName]                                                                         /v        Display verbose information in the output.

Key                                                                                                      /?         Help.
   /s     The name or IP address of a remote computer. (Do not                                      Administrator privileges are required to run the OPENFILES command. This can be used to
use backslashes.) default=local computer.                                                           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.
   /u     Run the command with the account permissions of user.                                     Running openfiles.exe from within powershell allows the output to be assigned to a variable.
Default=current logged on user.                                                                     Examples
                                                                                                    PS C:> openfiles /query
      /p       The password of the user account specified with /u.                                  PS C:> openfiles /query /fo table /nh
                                                                                                    PS C:> $file_list = openfiles /query /s Server64 /fo CSV /v /nh
   /fo    The format to use for the query output. Valid values                                      C:> openfiles /query /fo list /v
are TABLE, LIST, and CSV. Default=TABLE.                                                            C:> openfiles /query /s Server64 /u SS64DomFileAdmin /p password1
Windows Command Prompt                                                        www.nubielab.com                                                                                           Page 43
Firewalls
PS C:> openfiles /disconnect /id 1                                                                     Like tracert PathPing uses Internet Control Message Protocol (ICMP) over TCP/IP. Many
PS C:> openfiles /disconnect /a mike                                                                   firewalls will block ICMP traffic by default. If an attacker is able to forge ICMP redirect packets,
C:> openfiles /disconnect /o read/write                                                                he or she can alter the routing tables on the host and possibly subvert the security of the host by
C:> openfiles /disconnect /op "c:workfinance.xls"                                                    causing traffic to flow via a path you didn't intend.
C:> openfiles /disconnect /s Server64 /u SS64DomFileAdmin /id 5                                       PERMS.exe (Windows 2000)
C:> openfiles /disconnect /s Server64 /u SS64DomFileAdmin /p password1 /id *                          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
PATHPING                                                                                                         PERMS [account] [path] options
Trace route and provide network latency and packet loss for each router and link in the path.
Combines the functionality of PING and TRACERT.                                                         Key
Syntax                                                                                                        account : username or [domain|computer]username
        PATHPING [-n] [-h max_hops] [-g host_list] [-p period]
             [-q num_queries] [-w timeout] [-i IPAddress] [-4 ] [-6                                           path      : name of a file or folder in any legal format
][TargetName]                                                                                                             including UNC names
                                                                                                                          Wildcards are permitted.
Key
     -g host_list - Loose source route along host-list.                                                       /i        : interactively logged on to the computer
     -h max_hops - Maximum number of hops to search for target.                                                           where the path resides.
     -i address          - Use the specified source address.                                                              (rather than being connected via the network)
     -n                  - Do not resolve addresses to hostnames.
     -p period           - Wait period milliseconds between pings.                                            /s        : include subfolders
     -q num_queries - Number of queries per hop.
     -w timeout          - Wait timeout milliseconds for each reply.                                    Access       Description
     -P        - Test for RSVP PATH connectivity.
     -R        - Test if each hop is RSVP aware.                                                        R     Read file/folder.
     -T        - Test connectivity to each hop with Layer-2 priority
tags.                                                                                                   W     Write file/folder.
     -4        - Force using IPv4.
     -6        - Force using IPv6.                                                                      X     Execute file.
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.                           D Delete file or folder. May be inherited from the parent
Pathping sends multiple Echo Request messages to each router between a source and destination           folder
over a period of time and computes aggregate results based on the packets returned from each               via 'Delete Subfolder and Files' permission.
router.
Pathping performs the equivalent of the tracert command by identifying which routers are on the         P     Change Permission.
path.
To avoid network congestion and to minimize the effect of burst losses, pings should be sent at a       O     Take Ownership.
sufficiently slow pace (not too frequently.)
When -p is specified, pings are sent individually to each intermediate hop. When -w is specified,       A     General All
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.                                                             -     No Access


Windows Command Prompt                                                           www.nubielab.com                                                                                                 Page 44
*     The specified user is the owner of the file or folder.                                  Counter is the full name of a performance counter in the
                                                                                              format:"ComputerObject(Instance)Counter"
#     A group the user is a member of owns the file or folder.                                e.g. "Server1Processor(0)% User Time".
                                                                                              Examples
? Permisssions cannot be determined.                                                          Display % Processor time until interrupted:
TypePerf.exe                                                                                  C:> typeperf "Processor(_Total)% Processor Time"
Write performance data to the command window or to a log file.To stop Typeperf, press         Gather 600 samples of % Processor time on the local computer (this will take 10 minutes):
CTRL+C.                                                                                       C:> typeperf "processor(_Total)% Processor Time" -O C:SS64demo1.csv -SC 600
Syntax                                                                                        Gather samples of all the counters listed in counters.txt :
        typeperf counter [counter ...] [options]                                              C:> typeperf -cf counters.txt -si 5 -sc 50 -o C:SS64demo2.csv

         typeperf -cf filename           [options]
                                                                                              PING
         typeperf -q [object] [options]                                                       Test a network connection - if successful, ping returns the ip address.
                                                                                              Syntax
         typeperf -qx [object] [options]                                                               PING [options] destination_host

Key                                                                                           Options
   counter                        The Performance counters to monitor.                               -w timeout             Timeout in milliseconds to wait for each
   -f {CSV|TSV|BIN|SQL}           Output file format. Default is CSV.                         reply.
   -cf filename                   File containing performance counters to                            -i TTL                 Time To Live.
monitor, one per line.                                                                               -v TOS                 Type Of Service.
   -si [[hh:]mm:]ss               Time between samples. Default is 1                                 -a                     Resolve addresses to hostnames.
second.                                                                                              -n count               Number of echo requests to send.
   -o filename                    Path of output file or SQL database.                               -t                     Ping the destination host until interrupted.
                                  Default is STDOUT.                                                 -l size                Send buffer size.
      -q [object]                 List installed counters (no instances).                            -f                     Set Don't Fragment flag in packet.
                                  To list counters for one object,                                   -r count               Record route for count hops.
                                  include the object name, such as                                   -s count               Timestamp for count hops.
Processor.                                                                                           -j host_list           Loose source route along host_list.
   -qx [object]                   List installed counters with instances.                            -k host_list           Strict source route along host_list.
                                  To list counters for one object,                            destination_host The name of the remote host
                                  include the object name, such as                            A response of "Request timed out" means there was no response to the ping attempt in the
Processor.                                                                                    default time period of one second.
   -sc samples                    Number of samples to collect. Default is                    If the latency of the response is more than one second. Use the -w option on the ping command
                                  to sample until CTRL+C.                                     to increase the time-out. For example, to allow responses within five seconds, use ping -w 5000.
   -config filename               Settings file containing command                            A successful PING does NOT always return an %errorlevel% == 0
options.                                                                                      Therefore to reliably detect a successful ping - pipe the output into FIND and look for the text
   -s computer_name     Server to monitor if no server is                                     "TTL"
specified in the counter path.
   -y                   Answer yes to all questions without                                   Note that "Reply" in the output of PING does not always indicate a positive response. You may
prompting.                                                                                    receive a message from a router such as: Reply from 192.168.1.254: Destination Net
   -?                   Display context sensitive help.                                       Unreachable.
                                                                                              Four steps to test an IP connection with ping:


Windows Command Prompt                                                     www.nubielab.com                                                                                          Page 45
1) Ping the loopback address to verify that TCP/IP is installed and configured correctly on the       Syntax:
local computer.
PING 127.0.0.1                                                                                           REG QUERY [ROOT]RegKey /v ValueName [/s]
                                                                                                         REG QUERY [ROOT]RegKey /ve --This returns the (default)
2) Ping the IP address of the local computer to verify that it was added to the network correctly.    value
PING IP_address_of_local_host
                                                                                                         REG ADD [ROOT]RegKey /v ValueName [/t DataType] [/S
3) Ping the IP address of the default gateway to verify that the default gateway is functioning and   Separator] [/d Data] [/f]
that you can communicate with a local host on the local network.                                         REG ADD [ROOT]RegKey /ve [/d Data] [/f] -- Set the
PING IP_address_of_default_gateway                                                                    (default) value

4) Ping the IP address of a remote host to verify that you can communicate through a router.             REG DELETE [ROOT]RegKey /v ValueName [/f]
PING IP_address_of_remote_host                                                                           REG DELETE [ROOT]RegKey /ve [/f] -- Remove the (default)
                                                                                                      value
                                                                                                         REG DELETE [ROOT]RegKey /va [/f] -- Delete all values under
Examples                                                                                              this key
PING -n 1 -w 7500 Server_06
                                                                                                         REG COPY [SourceMachine][ROOT]RegKey
PING -w 7500 MyHost |find "TTL=" && ECHO MyHost found                                                 [DestMachine][ROOT]RegKey

PING -w 7500 MyHost |find "TTL=" || ECHO MyHost not found                                                   REG   EXPORT [ROOT]RegKey FileName.reg
                                                                                                            REG   IMPORT FileName.reg
PING -n 5 -w 7500 www.microsoft.com                                                                         REG   SAVE [ROOT]RegKey FileName.hiv
                                                                                                            REG   RESTORE MachineName[ROOT]KeyName FileName.hiv
PING -n 5 -w 7500 microsoft.com
Script to monitor your connection to a website (example.com) every 15 seconds:                              REG LOAD FileName KeyName
@Echo off                                                                                                   REG UNLOAD KeyName
Echo Logging ping responses, press CTRL-C to stop
:start                                                                                                   REG COMPARE [ROOT]RegKey [ROOT]RegKey [/v ValueName]
 Ping -n 1 example.com | find "TTL=" >>c:pingtest.txt                                                [Output] [/s]
 Echo .                                                                                                  REG COMPARE [ROOT]RegKey [ROOT]RegKey [/ve] [Output] [/s]
 Ping -n 16 127.0.0.1>nul
goto start                                                                                            Key:
The script above can be used to test an Internet connection, just replace example.com with your          ROOT :
ISP's Default Gateway IP address. This represents the first physical device on the ISP's side of                   HKLM    =   HKey_Local_machine (default)
your connection. You can find the Default Gateway on your router status screen.                                    HKCU    =   HKey_current_user
Note: some ISP’s or network admins may not appreciate you performing frequent or continual                         HKU     =   HKey_users
pings to their server, try not to overdo it!                                                                       HKCR    =   HKey_classes_root
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              ValueName : The value, under the selected RegKey, to edit.
equal to a distance of 930 Miles, travelling a straight line route at the speed of light.                               (default is all keys and values)

                                                                                                            /d Data       : The actual data to store as a "String", integer
REG.exe                                                                                               etc
Read, Set or Delete registry keys and values, save and restore from a .REG file.
Windows Command Prompt                                                          www.nubielab.com                                                                       Page 46
/f        : Force an update without prompting "Value exists,                                       REG COPY Wks580HKCUSoftwareSS64 HKCUSoftwareSS64
overwrite Y/N"                                                                                        REG COPY HKCUSoftwareSS64 HKCUSoftwareSS64Copy

   Machine : Name of remote machine - omitting defaults to                                          REG EXPORT HKCUSoftwareSS64 C:MyReg.REG
current machine.                                                                                      REG IMPORT C:MyReg.REG
                   Only HKLM and HKU are available on remote                                          REG SAVE HKCUSoftwareSS64 C:MyRegHive.hiv
machines.                                                                                             REG RESTORE Wks580HKCUSoftwareSS64 C:MyRegHive.hiv
                                                                                                      Run a script at first logon (Run Once) to do this we edit the Default User profile by temporarily
    FileName        : The filename to save or restore a registry hive.                                loading it as ZZZ:
                                                                                                      REG LOAD HKUZZZ "C:Documents and SettingsDefault
   KeyName          : A key name to load a hive file into. (Creating a                                UserNTUSER.DAT"
new key)                                                                                              REG ADD
                                                                                                      HKUZZZSOFTWAREMicrosoftWindowsCurrentVersionRunOnce /v
    /S              : Query all subkeys and values.                                                   newUserProfile /t REG_EXPAND_SZ /d "D:setup.cmd" /f
                                                                                                      REG UNLOAD HKUZZZ
   /S Separator : Character to use as the separator in
REG_MULTI_SZ values
                  the default is "0"                                                                 REGEDIT
                                                                                                      Import, export or delete registry settings from a text (.REG) file
   /t DataType          : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ |                              Syntax
REG_MULTI_SZ                                                                                                   Export the Registry (all HKLM plus current user)
                                                                                                               REGEDIT /E pathname
   Output    : /od (only differences) /os (only matches) /oa
(all) /on (no output)                                                                                           Export part of the Registry
                                                                                                                REGEDIT /E pathname "RegPath"
Notes:
Any of the above commands can be run against a remote machine by adding MachineName to                        Import a reg script
the command line, assuming the Remote Registry Service is running.                                              REGEDIT pathname
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.                    Silent import
To include a quote mark (") in the data, prefix it with the escape character () e.g. "Here is " a             REGEDIT /S pathname
quote"
Enclose ValueNames that contain the  character in single quotes.                                               Start the regedit GUI
REG RESTORE has a tendency not to work, possibly due to firewall issues, Export and Import                      REGEDIT
are much more reliable.
Examples                                                                                                        Open multiple copies of GUI (XP and 2003 only)
REG QUERY HKCUConsole                                                                                         REGEDIT -m
REG QUERY HKCUConsole /v ScreenBufferSize
REG ADD HKCUSoftwareSS64 /v Sample /d "some test data"                                              Key
REG QUERY HKCUSoftwareSS64 /v Sample                                                                      /E : Export

REG ADD HKLMSoftwareDiLithium /v WarpSpeed /t REG_BINARY /d                                            /S : Silent Import
ffffffff                                                                                              How to add keys and values from the registry:
REG QUERY HKLMSoftwareDiLithium /v WarpSpeed
                                                                                                      Create a text file like this:

Windows Command Prompt                                                           www.nubielab.com                                                                                              Page 47
Windows Registry Editor Version 5.00                                                                       /s                  Silent - no dialogue boxes.
[HKEY_CURRENT_USERSomeKey]                                                                                /c                  Console output.
"SomeStringValue"="Hello"                                                                                  /n                  Don't call DllRegisterServer
When double clicking this .reg file the key and value will be added.                                       /i                  Call DllInstall (or DllUninstall if /u is
Alternatively run REGEDIT MYKEY.REG from the command line.                                             specified)
How to delete keys and values from the registry:                                                          Command_Line An optional command line for DllInstall
                                                                                                       Examples
Create a reg file like this, notice the hyphen inside the first bracket                                Unregister (disable) XP Zip folders
Windows Registry Editor Version 5.00                                                                   REGSVR32 /u C:WindowsSystem32zipfldr.dll
[-HKEY_CURRENT_USERSomeKey]                                                                           Unregister (Disable) CAB file viewer:
When double clicking this .reg file the key "SomeKey" will be deleted along with all string,           REGSVR32 /u C:WindowsSystem32cabview.dll
binary or Dword values in that key.                                                                    Register (enable) XP Zip folders
                                                                                                       REGSVR32 zipfldr.dll
If you want to just delete values, leaving the key in place, set the value you want to delete = to a   Register (enable) CAB file viewer:
hyphen                                                                                                 REGSVR32 cabview.dll
e.g.                                                                                                   Register Windows Update DLLs (for those times when XP repair breaks Windows Update)
Windows Registry Editor Version 5.00                                                                   regsvr32 /s wuapi.dll
[HKEY_CURRENT_USERSomeKey]                                                                            regsvr32 /s wuaueng1.dll
"SomeStringValue"=-                                                                                    regsvr32 /s wuaueng.dll
Again double clicking this .reg file will delete the values specified, or you can use REGEDIT /s       regsvr32 /s wucltui.dll
MyDeleteScript.REG                                                                                     regsvr32 /s wups2.dll
                                                                                                       regsvr32 /s wups.dll
Compare the Registry of two machines                                                                   regsvr32 /s wuweb.dll
Windiff is your friend, this simple GUI utility from the resource kit will list all the differences.   Register DAO 3.6 (Data Access Objects):

Comments                                                                                               REGSVR32 "C:Program FilesCommon FilesMicrosoft SharedDAODAO360.DLL"
Within a registry file, comments can be preceded by "; "
e.g.
;
; Turn the NUMLOCK on at login
;
[HKEY_CURRENT_USERControl PanelKeyboard]
"InitialKeyboardIndicators"="2"                                                                        REGINI (Resource kit)
Under Windows NT 4 all registry scripts start with: REGEDIT4                                           Change Registry Permissions.
(This version string will also work in XP and later versions of Windows.)                              Syntax
REGSVR32                                                                                                      REGINI [-m machinename | -h hivefile hiveroot | -w
Register or unregister a DLL.                                                                          Win95Directory]
Syntax                                                                                                                    [-i n] [-o outputWidth]
         REGSVR32 [/U] [/S] [/C] [/I:[Command_Line]] DLL_Name                                                             [-b] textFiles...

           REGSVR32 [/U] [/S] [/C] /N /I:[Command_Line] DLL_Name                                       Key
                                                                                                             -m   A remote computer.
Key
                                                                                                             -h   The local hive to manipulate.
      /u               Unregister Server.

Windows Command Prompt                                                             www.nubielab.com                                                                                    Page 48
-w      Path to Windows 95 system.dat / user.dat files                                          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.
    -i n The display indentation multiple.                       Default is 4
                                                                                                    Indentation is used to indicate the tree structure of registry keys The REGDMP program uses
   -o outputWidth                                                                                   indentation in multiples of 4. You may use hard tab characters for indentation, but embedded
          How wide the output is to be. By default the                                              hard tab characters are converted to a single space regardless of their position
          outputWidth is set to the width of the console window
if standard                                                                                         Values should come before child keys, as they are associated with the previous key at or above
          output has not been redirected to a file. In the                                          the value's indentation level.
latter case, an
          outputWidth of 240 is used.                                                               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.
   -b     Make REGINI backward compatible with older versions of
REGINI that                                                                                         Key names can be followed by an Access Control List (ACL) which is a series of decimal
          did not strictly enforce line continuations and quoted                                    numbers, separated by spaces, bracketed by a square brackets (e.g. [8 4 17]). The valid numbers
strings                                                                                             and their meanings are:
          Specifically, REG_BINARY, REG_RESOURCE_LIST and                                                                  1 - Administrators Full Access
          REG_RESOURCE_REQUIREMENTS_LIST data types did not need                                                           2 - Administrators Read Access
line                                                                                                                       3 - Administrators Read and Write Access
          continuations after the first number that gave the                                                               4 - Administrators Read, Write and Delete Access
size of the data.                                                                                                          5 - Creator Full Access
            It just kept looking on following lines until it                                                               6 - Creator Read and Write Access
found enough data                                                                                                          7 - World Full Access
            values to equal the data length or hit invalid input.                                                          8 - World Read Access
Quoted                                                                                                                     9 - World Read and Write Access
            strings were only allowed in REG_MULTI_SZ. They                                                                10 - World Read, Write and Delete Access
could not be                                                                                                               11 - Power Users Full Access
            specified around key or value names, or around values                                                          12 - Power Users Read and Write Access
for REG_SZ or                                                                                                              13 - Power Users Read, Write and Delete Access
            REG_EXPAND_SZ Finally, the old REGINI did not                                                                  14 - System Operators Full Access
support the semicolon                                                                                                      15 - System Operators Read and Write Access
            as an end of line comment character.                                                                           16 - System Operators Read, Write and Delete
                                                                                                    Access
    textFiles One or more ANSI or Unicode text files with                                                                  17 - System Full Access
registry data.                                                                                                             18 - System Read and Write Access
The easiest way to understand the format of the input textFile is to use the REGDMP command                                19 - System Read Access
with no arguments to dump the current contents of                                                                          20 - Administrators Read, Write and Execute Access
your NT Registry to standard out. Redirect standard out to a file and this file is acceptable as                           21 - Interactive User Full Access
input to REGINI                                                                                                            22 - Interactive User Read and Write Access
                                                                                                                           23 - Interactive User Read, Write and Delete
Some general rules are:                                                                             Access
Semicolon character is an end-of-line comment character, provided it is the first non-blank         If there is an equal sign on the same line as a left square bracket then the equal sign takes
character on a line                                                                                 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
Backslash character is a line continuation character. All characters from the backslash up to but   under it.

Windows Command Prompt                                                         www.nubielab.com                                                                                                Page 49
For registry values, the syntax is:                                                 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
                     value Name = type data                                                         number of data bytes, excluding the first number. After the first number must come enough
Leading spaces, spaces on either side of the equal sign and spaces between the type keyword and     numbers to fill the value. Each number represents one DWORD or 4 bytes. So if the first number
data are ignored, unless the value name                                                             was 0x5 you would need two more numbers after that to fill the 5 bytes. The high order 3 bytes
is surrounded by quotes. If the text to the right of the equal sign is the string DELETE, then      of the second DWORD would be ignored.
REGINI will delete the value.
                                                                                                    Whenever specifying a registry path, either on the command line or in an input file, the
The value name may be left off or be specified by an at-sign character which is the same thing,     following prefix strings can be used:
namely the empty value name. So the following two lines are identical:                                   HKEY_LOCAL_MACHINE
                                                                                                         HKEY_USERS
= type data                                                                                              HKEY_CURRENT_USER
@ = type data                                                                                            USER:

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.                                        Each of these strings can stand alone as the key name or be
Valid value types and format of data that follows are:                                              followed
                                                                                                        a backslash and a subkey path.
                     REG_SZ text                                                                    There are several versions of regini with different syntax - the resource kit includes a word
                     REG_EXPAND_SZ text                                                             document with help and examples.
                     REG_MULTI_SZ "string1" "str""ing2" ...
                     REG_DATE mm/dd/yyyy HH:MM DayOfWeek
                     REG_DWORD numberDWORD
                     REG_BINARY numberOfBytes numberDWORD(s)...
                                                                                                    REN
                     REG_NONE           (same format as REG_BINARY)                                 Rename a file or files.
                     REG_RESOURCE_LIST (same format as REG_BINARY)                                     REN [drive:][path]old_filename new_filename
                     REG_RESOURCE_REQUIREMENTS      (same format as                                 RENAME is a synonym for REN
REG_BINARY)
                     REG_RESOURCE_REQUIREMENTS_LIST (same format as                                 You cannot specify a different drive or path for `new_filename` - use the MOVE command
REG_BINARY)                                                                                         instead.
                     REG_FULL_RESOURCE_DESCRIPTOR                    (same format as
REG_BINARY)                                                                                         Both the source and/or destination may include wildcards.
                     REG_QWORD numberQWORD                                                          e.g.
                     REG_MULTISZ_FILE fileName                                                           REN *.txt *.xyz
                     REG_BINARYFILE fileName                                                             REN c:MyFile.txt *.xyz
                                                                                                         REN c:MyFile.txt ????.xyz
If no value type is specified, default is REG_SZ                                                    "We may dig in our heels and dare life never to change, but, all the same, it changes under our
For REG_SZ and REG_EXPAND_SZ, if you want leading or trailing spaces in the value text,             feet like sand under the feet of a sea gazer as the tide runs out. Life is forever undermining us.
surround the text with quotes. The value text                                                       Life is forever washing away our castles, reminding us that they were, after all, only sand and
can contain any number of imbedded quotes, and REGINI will ignore them, as it only looks at         sea water." - Erica Jong (Parachutes and Kisses)
the first and last character for quote characters.
                                                                                                    REPLACE
For REG_MULTI_SZ, each component string is surrounded by quotes. If you want an imbedded            Replace or update one file with another
quote character, then double quote it, as in string2 above.                                         Syntax


Windows Command Prompt                                                          www.nubielab.com                                                                                               Page 50
REPLACE Source_PathName Destination_path [/A] [/P] [/R]
[/W]                                                                                                  RMDIR is a synonym for RD

      REPLACE Source_PathName Destination_path [/P] [/R] [/S]
[/W] [/U]
                                                                                                      ROUTE.exe
Key                                                                                                   Manipulate network routing tables. Route packets of network traffic from one subnet to another
      path : The folder where files are to be replaced.                                               by modifying the route table.
                                                                                                      Syntax
      /A    : Add any missing files.
                                                                                                         Display route details:
      /P    : Prompt for confirmation (each file)                                                           ROUTE [-f] PRINT [destination_host] [MASK
                                                                                                      subnet_mask_value] [gateway]
      /R    : Replace even Read-only files                                                                     [METRIC metric] [IF interface_no.]

      /S    : Include all subfolders of the destination.                                                 Add a route:
                                                                                                            ROUTE [-f] [-p] ADD [destination_host] [MASK
      /W    : Wait for you to insert a floppy disk.                                                   subnet_mask_value] [gateway]
                                                                                                               [METRIC metric] [IF interface_no.]
    /U      : Replace (update) only files that are older than the
source.                                                                                                  Change a route:
Limitations:                                                                                                ROUTE [-f] CHANGE [destination_host] [MASK
                                                                                                      subnet_mask_value] [gateway]
When replacing in all subdirectories (/S ) you cannot ADD files (/A) or restrict to replacing older            [METRIC metric] [IF interface_no.]
files (/U)
RD                                                                                                       Delete a route:
Delete folder(s)                                                                                            ROUTE [-f] DELETE [destination_host] [MASK
Syntax                                                                                                subnet_mask_value] [gateway]
          RD pathname                                                                                          [METRIC metric] [IF interface_no.]
          RD /S pathname
          RD /S /Q pathname                                                                           key
                                                                                                         -f              Clear (flush) the routing tables of all gateway
Key                                                                                                   entries.      If this is
      /S   : Delete all files and subfolders                                                                             used in conjunction with one of the commands, the
             in addition to the folder itself.                                                        tables are
             Use this to remove an entire folder tree.                                                                      cleared prior to running the command.

    /Q : Quiet - do not display YN confirmation                                                          destination_host
Place any long pathnames in double quotes.                                                                           The address (or set of addresses) that you want
                                                                                                      to reach.
RD does not support wildcards but you can remove several folders in one command by listing
the pathname to each.                                                                                    -p                 Create a persistent route - survives system
e.g.                                                                                                  reboots.
                                                                                                                            (not supported in Windows 95)
RD c:docsJan c:docsFeb "c:My DocumentsMar"

Windows Command Prompt                                                          www.nubielab.com                                                                                            Page 51
subnet_mask_value                                                                                        /P [password]                Password for the given user (will prompt
                The subnet mask value for this route entry.                                           if omitted)
                This defines how many addresses are there.                                                   /FO format                   Output format: TABLE, LIST or CSV
                If not specified, it defaults to 255.255.255.255.                                            /NH                          No "Column Header" in the Table/CSV
                                                                                                      output
    gateway            The gateway.                                                                   The output includes OS configuration, security info, product ID, RAM, disk space, and network
                                                                                                      cards.
   interface           The interface number (1,2,...) for the specified                               Examples
route.                                                                                                SYSTEMINFO
                       If the option `IF interface_no` is not given,                                  SYSTEMINFO |find "Total Physical Memory:"
ROUTE will try                                                                                        SYSTEMINFO /S wkstn6324
                       to find the best interface available.                                          SYSTEMINFO /S wkstn6325 /FO CSV /NH >>pcaudit.csv
                                                                                                      TASKLIST
    metric              The metric, ie. cost for the destination.                                     TaskList displays all running applications and services with their Process ID (PID) This can be
Note that routes added to the table are not made persistent unless the -p switch is specified. Non-   run on either a local or a remote computer.
persistent routes only last until the computer is rebooted.                                           Syntax
Symbolic names used for Destination_Host are looked up in the network database file                            tasklist options
NETWORKS.
                                                                                                      Options:
The symbolic names for gateway are looked up in the host name database file HOSTS.
                                                                                                           /s computer       Name or IP address of a remote computer
If the command is PRINT or DELETE. Destination or gateway can be a wildcard ('*'), or the                                    don't use backslashes. Default = local computer.
gateway argument may be omitted.
                                                                                                           /u domainuser [/p password]]
An IP address mask of 0.0.0.0 means everything. (rather like the *.* wildcard). In other words it                       Run under a different account
says: When matching this pattern, don't worry about matching any of the bits - everything
matches.                                                                                                 /svc                List information for each process without
                                                                                                      truncation.
If Destination_Host contains a * or ?, it is treated as a shell pattern, and only matching                                   Valid when /fo=TABLE. Cannot be used with /m or
destination routes are printed. The '*' matches any string, and '?' matches any one char.             /v
Examples:
157.*.1                                                                                                  /m [ModuleName]
157.*                                                                                                                 Show the processes that include the given
127.*                                                                                                 module.
*224*
SYSTEMINFO                                                                                                 /v                Verbose task information
List system configuration
Syntax                                                                                                     /fo {TABLE|LIST|CSV}]
          SYSTEMINFO [/S system [/U username [/P [password]]] ]                                                         Output format, the default is TABLE.
                                [/FO format] [/NH]
                                                                                                         /nh                 No Headers in the output (does not apply to LIST
Key:                                                                                                  output)
       /S   system                 Remote system to connect to.
       /U   [domain]user          User context under which to execute.                                    /fi FilterName [/fi FilterName2 [ ... ]]
                                                                                                                        Apply one of the Filters below:

Windows Command Prompt                                                          www.nubielab.com                                                                                             Page 52
/FI     filter           Display a set of tasks that match a
                      Imagename      eq, ne                    String                                     given criteria specified by the
                      PID            eq, ne, gt, lt, ge, le    Positive      filter.
integer.
                      Session        eq, ne, gt, lt, ge, le    Any valid         /PID process id          The PID of the process to be
session number.                                                              terminated.
                      SessionName eq, ne                       String
                      Status      eq, ne                       RUNNING |         /IM image name           The image name of the process to be
NOT RESPONDING                                                               terminated.
                      CPUTime        eq, ne, gt, lt, ge, le    Time                                       Wildcard '*' can be used to specify
hh:mm:ss                                                                     all image names.
                      MemUsage       eq, ne, gt, lt, ge, le    Any valid
integer.                                                                         /T                        Tree kill: terminates the specified
                      Username       eq, ne                    User name     process
([Domain]User).                                                                                           and any child processes which were
                      Services    eq, ne                       String        started by it.
                      Windowtitle eq, ne                       String
                      Modules     eq, ne                       String          Filters       Apply one of the Filters below:
Examples:
tasklist /svc                                                                                Imagename   eq, ne                   String
                                                                                             PID         eq, ne, gt, lt, ge, le   Positive
tasklist /v /fi "STATUS eq running"                                          integer.
                                                                                           Session     eq, ne, gt, lt, ge, le Any valid
tasklist /v /fi "username eq ORACLE_SERVICE_ACCOUNT"                         session number.
WMIC can also list running processes and parameters:                                       Status      eq, ne                  RUNNING | NOT
WMIC /OUTPUT:C:ProcList.txt PROCESS get                                     RESPONDING
Caption,Commandline,Processid                                                              CPUTime     eq, ne, gt, lt, ge, le Time hh:mm:ss
TASKLIST                                                                                   MemUsage    eq, ne, gt, lt, ge, le Any valid
End one or more processes (by process id or image name).                     integer.
Syntax                                                                                     Username    eq, ne                  User name
        TASKKILL [/S system [/U username [/P [password]]]]                   ([Domain]User).
            { [/FI filter] [/PID processid | /IM imagename] } [/F]                         Services    eq, ne                  String The
[/T]                                                                         service name
                                                                                           Windowtitle eq, ne                  String
Options                                                                                    Modules     eq, ne                  String The DLL
    /S     system               The remote system to connect to.             name
                                                                             Examples:
    /U     [domain]user        The user context under which                 Examples:
                                the command should execute.                       TASKKILL /S system /F /IM notepad.exe /T
                                                                                  TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
    /P   [password]             The password. Prompts for input if                TASKKILL /F /IM notepad.exe /IM mspaint.exe
omitted.                                                                          TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"
                                                                                  TASKKILL /F /FI "USERNAME eq NT AUTHORITYSYSTEM" /IM
    /F                          Forcefully terminate the process(es).        notepad.exe


Windows Command Prompt                                    www.nubielab.com                                                                   Page 53
TASKKILL /S system /U domainusername /FI "USERNAME ne NT*"                                     This process relys on intermediate routers to return ICMP Time Exceeded messages. However,
/IM *                                                                                                 some routers do not return Time Exceeded messages for packets with expired TTL values and are
      TASKKILL /S system /U username /P password /FI "IMAGENAME eq                                    invisible to the tracert command. In this case, a row of asterisks (*) is displayed for that hop.
note*"                                                                                                Firewalls
TRACERT                                                                                               Many firewalls will block ICMP traffic by default. If an attacker is able to forge ICMP redirect
Trace Route - Find the IP address of any remote host. TRACERT is useful for troubleshooting           packets, he or she can alter the routing tables on the host and possibly subvert the security of the
large networks where several paths can be taken to arrive at the same point, or where many            host by causing traffic to flow via a path you didn't intend.
intermediate systems (routers or bridges) are involved.
Syntax                                                                                                Examples
         TRACERT [options] target_name                                                                 TRACERT www.doubleclick.net

Key                                                                                                    TRACERT 123.45.67.89
      target_name            The HTTP or UNC name of the host
                                                                                                       TRACERT local_server
Options:                                                                                              XCACLS.exe (Resource Kit)
    -d                       Do not resolve addresses to hostnames.                                   Display or modify Access Control Lists (ACLs) for files and folders.
                             (avoids performing a DNS lookup)                                         Syntax
                                                                                                               XCACLS filename [options]
    -h max_hops     Maximum number of hops to search for
target.(default=30)                                                                                              XCACLS filename

       -j host-listTrace route along given host-list.                                                 Key
                   up to 9 hosts in dotted decimal notation,                                             If no options are specified XCACLS will display the ACLs for
separated by spaces.                                                                                  the file(s)

      -w timeout               Wait timeout milliseconds for each reply.                                    options can be any combination of:
The functionality of TRACERT is the same under all versions of windows but the output is
cosmetically improved under XP.                                                                          /T        Traverse all subfolders and change all matching
Tracert uses the IP TTL field and ICMP error messages to determine the route from one host to         files found.
another through a network.
Care must be taken with tracert as it shows the optimal route, not necessarily the actual route. To         /E          Edit ACL instead of replacing it.
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.                          /x       Edit ACL instead of replacing it; affect only ACEs
This diagnostic tool determines the path taken to a destination by sending ICMP Echo Request          that this user already owns*
messages with varying Time to Live (TTL) values to the destination.
TTL (Time to Live) calculation                                                                              /R user     Revoke all access rights from the given user.
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.                       /D user     Deny specified user access, this will over-ride
When the TTL on a packet reaches 0, the router is expected to return an ICMP Time Exceeded                              all other permissions the user has.
message to the source computer.
Tracert determines the path by sending the first Echo Request message with a TTL of 1 and                   /C          Continue on access denied errors.
incrementing the TTL by 1 on each subsequent transmission until either the target host responds             /Y          Replace user's rights without verify
or the maximum number of hops is reached.
                                                                                                            /P user:permision[;FolderSpec]
                                                                                                                Replace user's rights. see /G option below

Windows Command Prompt                                                          www.nubielab.com                                                                                                Page 54
When xcacls is applied to the current folder only there is no inheritance and so no output.
    /G user:permision[;FolderSpec]                                                                    Versions:
        Grant specified user access rights, permision can be:                                         NTFS standards have changed with different versions of Windows and XCACLS has been
          r Read                                                                                      updated to suit, early versions of Xcacls may give unpredictable results against an NTFS v5
          c Change (write)                                                                            partition.
          f Full control                                                                              xcacls.vbs is described in Q825751 and can be downloaded here - xcacls.vbs is an unsupported
          p Change Permissions (Special access)                                                       utility that addresses a limitation with the original xcacls.exe, specifically the inability to append
          o Take Ownership (Special access)                                                           permissions to a folder whose child objects have the inheritance flag set. The .vbs version does
          x EXecute (Special access)                                                                  not suppport unc paths and is very slow to update multiple ACLs.
          e REad (Special access)                                                                     Examples:
          w Write (Special access)
          d Delete (Special access)                                                                   :: Allow guests the right to read and execute in MyFolder
          t Used only by FolderSpec. see below                                                        XCACLS MyFolder /E /G guests:rx

* Option only valid in Windows 2003                                                                   :: Allow guests the Full Control permission in MyFolder and all subfolders
FolderSpec is a permission applied to a folder. If FolderSpec is not specified then permission        XCACLS MyFolder /T /E /G guests:f
will apply to both files and folders.
This allows you to set different permissions that will apply (through inheritance) when new files     :: Grant guests only read access to all files in and below MyFolder,
are added to the folder.                                                                              :: new folders created will be Read Access only, new files will not inherit any rights.
                                                                                                      XCACLS MyFolder /T /P guests:R;Tr
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      :: Grant guests only execute access to all files in and below MyFolder
example ;TF will apply full control (but ;FT is not valid)                                            XCACLS MyFolder /T /P guests:x

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.
                                                                                                      XCOPY
                                                                                                      Copy files and/or directory trees to another folder. XCOPY is similar to the COPY command
Inheritance Errors                                                                                    except that it has additional switches to specify both the source and destination in detail.
"Permissions incorrectly ordered" - the quickest way to resolve or avoid these errors is to use the
newer iCACLS command instead of XCACLS.                                                               XCOPY is particularly useful when copying files from CDROM to a hard drive, as it will
Inherited folder permissions are displayed as:                                                        automatically remove the read-only attribute.
  OI - Object inherit                - This folder and files. (no inheritance                         Syntax
to subfolders)                                                                                                XCOPY source [destination] [options]
  CI - Container inherit - This folder and subfolders.
  IO - Inherit only                  - The ACE does not apply to the current                          Key
file/directory                                                                                              source           : Pathname for the file(s) to be copied.
These can be combined as folllows:                                                                          destination : Pathname for the new file(s).
  (OI)(CI)                  This folder, subfolders, and files.
  (OI)(CI)(IO) Subfolders and files only.                                                                   [options] can be any combination of the following:
        (CI)(IO) Subfolders only.
  (OI)        (IO) Files only.
                                                                                                            Source Options
So BUILTINAdministrators:(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)

Windows Command Prompt                                                          www.nubielab.com                                                                                                   Page 55
/A                 Copy files with the archive attribute set
(default=Y)                                                                       /Y           (Windows 2000 only) Suppress prompt to confirm
                                                                               overwriting a file.
      /M              Copy files with the archive attribute set and                            may be preset in the COPYCMD env variable.
                      turn off the archive attribute, use this option             /-Y          (Windows 2000 only) Prompt to confirm
                      when making regular Backups (default=Y)                  overwriting a file.

   /H                 Copy hidden and system files and folders                    /V            Verify that the new files were written
(default=N)                                                                    correctly.
                                                                                  /C            Continue copying even if an error occurs.
      /D:mm-dd-yyyy
                      Copy files that have   changed since mm-dd-yyyy.            /I            If in doubt always assume the destination is a
                      (files changed on or   after the specified date)         folder
                      If no date is given,   the default is 1 day ago                           e.g. when the destination does not exist.
                      (files changed on or   after 00:01 yesterday.)
                                                                                  /Z            Copy files in restartable mode. If the copy is
   /U                 Copy only files that already exist in                    interrupted part
destination.                                                                                    way through, it will restart if possible. (use
                                                                               on slow networks)
      /S              Copy folders and subfolders
                                                                                  /Q            Do not display file names while copying.
   /E                 Copy folders and subfolders, including Empty                /F            Display full source and destination file names
folders.                                                                       while copying.
                      May be used to modify /T.                                   /L            List only - Display files that would be copied.

      /EXCLUDE:file1[+file2][+file3]...                                           Destination Options

                     (Windows 2000 only) The files can each contain               /R            Overwrite read-only files.
one
                     or more full or partial pathnames to be excluded.            /T            Create folder structure, but do not copy files.
                     When any of these match any part of the absolute          Do not
path                                                                                            include empty folders or subfolders.
                     of a SOURCE file, then that file will be                                   /T /E will include empty folders and subfolders.
excluded.
               For example, specifying a string like obj or                     /K           Copy attributes. XCOPY will otherwise reset
.obj will exclude                                                              read-only attributes.
               all files underneath the directory obj or all
files with the                                                                    /N           If at all possible, use only a short filename
               .obj extension respectively.                                    (8.3) when creating
                                                                                               a destination file. This may be nececcary when
      Copy Options                                                             copying between disks
                                                                                               that are formatted differently e.g NTFS and
   /W                 Prompt you to press a key before starting to             VFAT, or when archiving
copy.                                                                                          data to an ISO9660 CDROM.
   /P                 Prompt before creating each file.

Windows Command Prompt                                      www.nubielab.com                                                                Page 56
/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:
                                                                                               Syntax
XCOPY C:utilsMyFile D:BackupCopyFile
                                                                                               Parameters
To copy a folder:                                                                              A parameter (or argument) is any value passed into a batch script:
                                                                                               C:> MyScript.cmd January 1234 "Some value"
XCOPY C:utils D:Backuputils /i                                                              Parameters may also be passed to a subroutine with CALL:
                                                                                               CALL :my_sub 2468
To copy a folder including all subfolders.                                                     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
XCOPY C:utils* D:Backuputils /s /i                                                         %* in a batch script refers to all the arguments (e.g. %1 %2 %3 %4 %5 ...%255)
                                                                                               Filename Parameter Extensions
The /i defines the destination as a folder.
                                                                                               When a parameter is used to supply a filename then the following extended syntax can be
Notes                                                                                          applied:

In many cases the functionality of XCOPY is superseded by ROBOCOPY.                            we are using the variable %1 (but this works for any parameter)

To force the overwriting of destination files under both NT4 and Windows2000 use the           %~f1 - expands %1 to a Fully qualified path name - C:utilsMyFile.txt
COPYCMD environment variable:
SET COPYCMD=/Y                                                                                 %~d1 - expands %1 to a Drive letter only - C:
This will turn off the prompt in Win2000 and will be ignored by NT4 (which overwrites by
default).                                                                                      %~p1 - expands %1 to a Path only - utils

When comparing Dates/Times the granularity (the finest increment of the timestamp) is 2        %~n1 - expands %1 to a file Name, or if only a path is present (with no trailing backslash) - the
seconds for a FAT volume and 0.1 microsecond for an NTFS volume.                               last folder in that path
The WinXP version of XCOPY will accept wildcards for the source e.g. *.txt
It is also more forgiving with trailing backslashes                                            %~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 57
Using CALL to jump to a subroutine
%~z1 - display the file size of %1                                                                              CALL :s_staff SMITH 100

%~$PATH:1 - search the PATH environment variable and expand %1 to the fully qualified                        Calling a subroutine from a FOR command
name of the first match found.                                                                                  FOR /F %%G IN ('DIR /b *.*') DO call :s_subroutine %%G
The modifiers above can be combined:

%~dp1 - expands %1 to a drive letter and path only                                                       Windows Environment Variables
%~nx2 - expands %2 to a file name and extension only                                                     Environment variables are mainly used within batch files, they can be created, modified and
When writing batch scripts it's a good idea to store parameter values in a variable using the SET        deleted using the SET command.
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.          Variables can be displayed using either SET or ECHO.
Note on short file/folder names:                                                                         Variables have a percent sign on both sides: %ThisIsAVariable%
There is a bug involving the ~s option - the displayed output may be wrong if the current                The variable name can include spaces, punctuation and mixed case: %_Another Ex.ample%
directory name is not the same as the 8.3 version of the directory.                                      This is unlike Parameter Variables which only have one % sign and are always one character
A workaround is to run command.com /c rem , which will change the current directory to 8.3               long: %A
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                                                                                                Standard (built-in) Environment Variables
FOR command parameters                                                                                                                                Default value:                 Default value:
                                                                                                                      Variable
The FOR command creates parameters which are identified with a letter rather than a number.                                                           Windows XP                    Windows 7/2008
These are easily confused with the parameter modifier letters described above.
                                                                                                                                             C:Documents and SettingsAll
Therefore when using FOR it's best to avoid the letters (a, d, f, n, p, s, t, x, z), apart from making    %ALLUSERSPROFILE%                                                    C:ProgramData
                                                                                                                                             Users
code easier to follow, this can avoid problems when running under NT 4 and Windows 2000:
                                                                                                                                             C:Documents and
%0 - the Batch Script itself                                                                                                                                                   C:Users{username}AppD
                                                                                                          %APPDATA%                          Settings{username}Application
                                                                                                                                                                               ataRoaming
                                                                                                                                             Data
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                                                                            C:Program FilesCommon
                                                                                                          %CommonProgramFiles%               C:Program FilesCommon Files
mapped drive.                                                                                                                                                                  Files
You cannot set the current directory to a UNC path but you can refer to other files in the same
                                                                                                                                             C:Program Files (x86)Common     C:Program Files
folder as the batch script by using this syntax:                                                          %COMMONPROGRAMFILES(x86)%
                                                                                                                                             Files                             (x86)Common Files
    CALL %0..SecondBatch.cmd
This can even be used in a subroutine, Echo %0 will give the call label but, echo "%~nx0" will            %COMPUTERNAME%                     {computername}                    {computername}
give you the filename of the batch script.
When the %0 variable is expanded in Windows XP, the result is enclosed in quotation marks.                                                                                     C:WindowsSystem32cm
                                                                                                          %COMSPEC%                          C:WindowsSystem32cmd.exe
Examples:                                                                                                                                                                      d.exe
Pass parameters from one batch to another:
          MyBatch.cmd SMITH 100                                                                           %HOMEDRIVE%                        C:                                C:
Or as part of a CALL :                                                                                                                       Documents and
          CALL MyBatch.cmd SMITH 100                                                                      %HOMEPATH%
                                                                                                                                             Settings{username}
                                                                                                                                                                               Users{username}
Passing values from one part of a script to another

Windows Command Prompt                                                             www.nubielab.com                                                                                                Page 58
N/A                                                             %WINDIR%                       C:Windows                        C:Windows
                           (but can be manually added
                                                           C:Users{username}AppD    1
                                                                                        Only on 64 bit systems, is used to store 32 bit programs.
 %LOCALAPPDATA%            LOCALAPPDATA=%USERPRO
                                                           ataLocal                   By default, files stored under Local Settings do not roam with a roaming profile.
                           FILE%Local
                           SettingsApplication Data)                                  %ERRORLEVEL% is a dynamic variable that is automatically set when a program exits.
                                                                                       Dynamic Variables
 %LOGONSERVER%             {domain_logon_server}         {domain_logon_server}     There are also 6 dynamic environment variables, these are computed each time the variable is
                                                                                       expanded.
                                                           C:WindowsSystem32;C:
                           C:WindowsSystem32;C:Windo                               n.b. you should not attempt to directly SET a dynamic variable.
                                                           Windows;C:WindowsSys
 %PATH%                    ws;C:WindowsSystem32Wbe
                                                           tem32Wbem;{plus
                           m;{plus program paths}                                      %CD% - The current directory (string).
                                                           program paths}

                                                           .COM; .EXE; .BAT; .CMD;     %DATE% - The current date using same region specific format as DATE.
                           .COM; .EXE; .BAT; .CMD; .VBS;
 %PATHEXT%                                                 .VBS; .VBE; .JS ; .WSF;
                           .VBE; .JS ; .WSF; .WSH;
                                                           .WSH; .MSC                  %TIME% - The current time using same format as TIME.

 %ProgramData%             N/A                             C:ProgramData              %RANDOM% - A random decimal number between 0 and 32767.
 %ProgramFiles%            C:Program Files                C:Program Files
                                                                                       %CMDEXTVERSION% - The current Command Processor Extensions version number.
                       1
 %ProgramFiles(x86)%       C:Program Files (x86)          C:Program Files (x86)
                                                                                       %CMDCMDLINE% - The original command line that invoked the Command Processor.
                                                           Code for current command    Pass a variable from one batch script to another
                           Code for current command
                                                           prompt format,usually       Where one batch script CALLs another it is recommended that you SETLOCAL in both scripts
 %PROMPT%                  prompt format,usually $P$G
                                                           $P$G                        to prevent any possible naming conflicts, so each script should start with:
                           C :>
                                                           C :>                        @ECHO OFF
                                                                                       SETLOCAL
                                                           %SystemRoot%system32
                                                                                       Then to pass a value back to the original calling script, finish the script with a line like:
 %PSModulePath%            N/A                             WindowsPowerShellv1.0
                                                                                       ENDLOCAL & SET _output=%_variable%
                                                           Modules
                                                                                       In the line above %_variable% is a local variable used and visible within just that one batch
 %Public%                  N/A                             C:UsersPublic             script
                                                                                       %_output% is an output variable that is passed back to the original calling script
 %SYSTEMDRIVE%             C:                              C:

 %SYSTEMROOT%              C:Windows                      C:Windows
                                                                                       Conditional Execution
                           C:Documents and
                                                           C:Users{Username}AppD
 %TEMP% and %TMP%          Settings{username}Local                                   Syntax
                                                           ataLocalTemp
                           SettingsTemp
                                                                                       An AND list of commands has the form
 %USERDOMAIN%              {userdomain}                    {userdomain}

 %USERNAME%                {username}                      {username}                           command1      && command2

                           %SystemDrive%Documents and     %SystemDrive%Users{use    command2 is executed if, and only if, command1 succeeds.
 %USERPROFILE%
                           Settings{username}             rname}


Windows Command Prompt                                              www.nubielab.com                                                                                         Page 59
A single & will always execute both commands                                                    To call a second batch file in a separate shell use CMD An important difference between CALL
      command1 & command2                                                                       and CMD is the exit behaviour if an error occurs.
                                                                                                     @ECHO off
                                                                                                     IF EXIST C:pagefile.sys CMD /C Second_Batch.cmd
An OR list of commands has the form                                                             Batch file Functions
                                                                                                Packaging up code into a discrete functions, each with a clear purpose is a very common
         command1       || command2                                                             programming technique. Re-using known, tested code, means you can solve problems very
                                                                                                quickly by just bolting together a few functions.
command2 is executed if, and only if, command1 fails                                            The CMD shell does not have any documented support for functions, but you can fake it by
Example                                                                                         passing arguments/parameters to a subroutine and you can use SETLOCAL to control the
   COPY Z:OracleTNSnames.ORA C:Oracle || ECHO The Copy                                      visibility of variables.
Failed                                                                                          At first glance building a function may look as simple as this:
                                                                                                :myfunct
Loops and subroutines                                                                           SETLOCAL
There are 2 ways to conditionally process commands in a batch file                              SET _var1=%1
                                                                                                SET _var2="%_var1%--%_var1%--%_var1%"
IF xxx ELSE yyy - will conditionally perform a command (or a set of commands)                   SET _result=%_var2%
                                                                                                ENDLOCAL
FOR aaa DO xxx - will conditionally perform a command several times (for a set of data, or a
set of files)                                                                                   but there is a problem, the ENDLOCAL command will throw away the _result variable and so
                                                                                                the function returns nothing.
Either of these can be combined with the CALL command to run a subroutine like this:            :myfunct2
    @echo off                                                                                   SETLOCAL
    IF EXIST C:pagefile.sys CALL :s_page_on_c                                                  SET _var1=%1
    IF EXIST D:pagefile.sys CALL :s_page_on_d                                                  SET _var2="%_var1%--%_var1%--%_var1%"
    GOTO :eof                                                                                   ENDLOCAL
                                                                                                SET _result=%_var2%
    :s_page_on_c                                                                                This version is getting close, but it still fails to return a value, this time because ENDLOCAL
    echo pagefile found on C: drive                                                             will throw away the _var2 variable
    GOTO :eof
                                                                                                The solution to this is to take advantage of the fact that the CMD shell evaluates variables on a
     :s_page_on_d                                                                               line-by-line basis - so placing ENDLOCAL on the same line as the SET statement(s) gives the
     echo pagefile found on D: drive                                                            result we want:
Without the : a second batch file will be called ...                                            :myfunct3
     @ECHO off                                                                                  SETLOCAL
     IF EXIST C:pagefile.sys CALL Second_Batch.cmd                                             SET _var1=%1
If the code does not need to return then use the GOTO statement like this:                      SET _var2="%_var1%--%_var1%--%_var1%"
     @ECHO off                                                                                  ENDLOCAL & SET _result=%_var2%
     IF EXIST C:pagefile.sys GOTO s_page_on_c
     ECHO pagefile not found                                                                    In examples above there are just 2 local variables (_var1 and _var2) but in practice there could
     GOTO :eof                                                                                  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.
    :s_page_on_c                                                                                In other words you can do this:
    ECHO pagefile found


Windows Command Prompt                                                       www.nubielab.com                                                                                            Page 60
@ECHO OFF                                                                                      IF "2" GEQ "15" echo "bigger"
SET _var1=64                                                                                   Will perform a character comparison and will echo "bigger"
SET _var2=123                                                                                  however the command
CALL :myfunct3 Testing                                                                         IF 2 GEQ 15 echo "bigger"
echo %_var1%                                                                                   Will perform a numeric comparison and works as expected.
echo %_result%                                                                                 This is opposite to the SET /a command where quotes are required.
goto :eof                                                                                      SET
                                                                                               Display, set, or remove CMD environment variables. Changes made with SET will remain only
                                                                                               for the duration of the current CMD session.
:myfunct3                                                                                      Syntax
SETLOCAL                                                                                                SET variable
SET _var1=%1                                                                                            SET variable=string
SET _var2="%_var1%--%_var1%--%_var1%"                                                                   SET /A variable=expression
ENDLOCAL & SET _result=%_var2%                                                                          SET "variable="
Using brackets to group expressions                                                                     SET /P variable=[promptString]
Brackets can be useful to make complex commands more readable and/or to span commands                   SET "
across several lines.
         (command)                                                                             Key
                                                                                                     variable    : A new or existing environment variable name
        (                                                                                            string      : A text string to assign to the variable.
            command )                                                                                expression: : Arithmetic Sum

e.g.                                                                                           Also see SetX, VarSearch and VarSubstring for more advanced
   IF EXIST C:pagefile.sys (                                                                  variable manipulation.
                                             ECHO pagefile found on C: drive)                  Variable names are not case sensitive but the contents can be. Variables can contain spaces.
The use of brackets is only required if the command is run over several lines e.g.             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
IF EXIST filename (                                                                            languages.
del filename                                                                                   To display current variables:
) ELSE (
echo The file was not found.                                                                   Type SET without parameters to display all the current environment variables.
)
The CMD shell statement does not use any great intelligence when evaluating brackets used as   Type SET with a variable name to display that variable SET _department
part of an IF or a FOR command, so for example the command below will fail:                    or use ECHO: ECHO [%_department%]
IF EXIST MyFile.txt (ECHO Some(more)Potatoes)
This version will work:                                                                        The SET command invoked with a string (and no equal sign) will display a wildcard list of all
IF EXIST MyFile.txt (ECHO Some[more]Potatoes)                                                  matching variables
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   Display variables that begin with 'P': SET p
misinterpreted by the command processor.                                                       Display variables that begin with an underscore SET _
Testing Numeric values                                                                         Examples
Do not use brackets or quotes if you are comparing numeric values with an IF command
e.g.                                                                                           Storing a text string:
IF (2) GEQ (15) echo "bigger"
or                                                                                             C:>SET _dept=Sales and Marketing
Windows Command Prompt                                                      www.nubielab.com                                                                                           Page 61
C:>set _                                                                                          ECHO (%substring%)
_dept=Sales and Marketing                                                                         Deleting an environment variable
One variable can be based on another, but this is not dynamic
E.g.                                                                                              Type SET with just the variable name and an equals sign:
C:>set xx=fish
C:>set msg=%xx% chips                                                                            SET _department=
C:>set msg
msg=fish chips                                                                                    Better still, to be sure there is no trailing space after the = use:
C:>set xx=sausage                                                                                (SET _department=)
C:>set msg                                                                                        or
msg=fish chips                                                                                    SET "_department="
C:>set msg=%xx% chips
C:>set msg                                                                                       Variable names can include Spaces
msg=sausage chips
Avoid starting variable names with a number, this will avoid the variable being mis-interpreted   A variable can contain spaces and also the variable name itself may contain spaces, therefore the
as a parameter                                                                                    following assignment:
%123_myvar% < > %1 23_myvar                                                                       SET my var=MyText
                                                                                                  will create a variable called "my var"
To display undocumented system variables:
    SET "                                                                                         Similarly
Prompt for user input                                                                             SET _var =MyText
@echo off                                                                                         will create a variable called "_var " - note trailing space
Set /P _dept=Please enter Department:
If "%_dept%"=="" goto :sub_error                                                                  To avoid problems with extra spaces appearing in your output, issue SET statements in
If /i "%_dept%"=="finance" goto sub_finance                                                       parentheses, like this
If /i "%_dept%"=="hr" goto sub_hr
goto:eof                                                                                          (SET _department=Some Text)
                                                                                                  Alternatively you can do
:sub_finance                                                                                      SET "_department=Some Text"
echo You chose the finance dept
goto:eof                                                                                          Note: if you wanted to actually include a bracket in the variable you need to use an escape
                                                                                                  character.
:sub_hr
echo You chose the hr dept                                                                        The SET command will set ERRORLEVEL to 1 if the variable name is not found in the current
The /P switch allows you to set a variable equal to a line of input entered by the user.          environment.
The PromptString is displayed before the user input is read. The PromptString can be empty.       This can be detected using the IF ERRORLEVEL command
The CHOICE command is an alternative to SET /P                                                    Arithmetic expressions (SET /a)
To place the first line of a file into a variable:
Set /P _MyVar=<MyFilename.txt                                                                     The expression to be evaluated can include the following operators:
CALL SET                                                                                              Multiply *
SET can be CALLed allowing a variable substring to be evaluated:                                      Divide         /
 SET start=10                                                                                         Add            +
 SET length=9                                                                                         Subtract -
 SET string=The quick brown fox jumps over the lazy dog                                               Modulus %
 CALL SET substring=%%string:~%start%,%length%%%

Windows Command Prompt                                                        www.nubielab.com                                                                                             Page 62
AND           &
    OR            |                                                                                So 0x12 = 022 = 18 decimal
    XOR           ^
    LSH           <<                                                                               The octal notation can be confusing - all numeric values that start with zeros are treated as octal
    RSH           >>                                                                               but 08 and 09 are not valid numbers because 8 and 9 are not valid octal digits.
    Multiply Variable *=
    Divide Variable              /=                                                                This is often a cause of error when performing date arithmetic. For example SET /a _day=07 will
    Add Variable                 +=                                                                return the value=7, but SET /a _day=09 will return an error.
    Subtract Variable -=
    AND Variable &=                                                                                Permanent Changes
    OR Variable           |=
    XOR Variable ^=                                                                                Changes made using the SET command are NOT permanent, they apply to the current CMD
    LSH Variable <<=                                                                               prompt only and remain only until the CMD window is closed.
    RSH Variable <<=                                                                               To permanently change a variable at the command line use SetX
SET /a calculations                                                                                or in the GUI - Control Panel, System, Environment, System/User Variables
Enclose any logical expressions in "quotes"
Several calculations can be put on one line if separated with commas.                              Changing a variable permanently with SetX will not affect any CMD prompt that is already
                                                                                                   open.
Warning: any SET /A calculation that returns a fractional result will be rounded down to the       Only new CMD prompts will get the new setting.
nearest whole integer.
Examples:                                                                                          You can of course use SetX in conjunction with SET to change both at the same time, but neither
    SET /A _result=2+4                                                                             SET or SetX will affect other CMD sessions that are already running. When you think about it -
    (=6)                                                                                           this is a good thing.
    SET /A _result=5                                                                               It is also possible (although undocumented) to add permanent env variables to the registry
    (=5)                                                                                           [HKEY_CURRENT_USEREnvironment]
    SET /A _result+=5                                                                              (using REGEDIT)
    (=10)                                                                                          System Environment variables can also be found in
                                                                                                   [HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment]
   SET /A _result="2<<3"
   (=16)   { 2 Lsh 3 = binary 10 Lsh 3 = binary 10000 = decimal                                    Autoexec.bat
16 }
                                                                                                   Any SET statement in c:autoexec.bat may be parsed at boot time
     SET /A _result="5%%2"
                                                                                                   Variables set in this way are not available to 32 bit gui programs - they won't appear in the
     (=1)        { 5/2 = 2 + 2 remainder 1 = 1 }
                                                                                                   control panel.
Modulus operator - note that in a batch script, (as opposed to on the command-line), you need to   They will appear at the CMD prompt.
double up the % to %%
SET /A will treat any character string in the expression as an environment variable name. This     If autoexec.bat CALLS any secondary batch files, the additional batch files will NOT be parsed
allows you to do arithmetic with environment variable values without having to type any % signs    at boot.
to get the values. SET /A _result=5 + _MyVar                                                       This behaviour can be useful on a dual boot PC.
Leading Zero will specify Octal                                                                    If Command Extensions are disabled all SET commands are disabled other than simple
                                                                                                   assignments like:
Numeric values are decimal numbers, unless prefixed by                                             _variable=MyText
0x for hexadecimal numbers,
                                                                                                   Redirection
0 for octal numbers.

Windows Command Prompt                                                        www.nubielab.com                                                                                                Page 63
command > filename         Redirect command output to a file               (command)>filename 2> nul                 Redirect output to file but
                                                                            suppress CMD.exe errors
   command >> filename            APPEND into a file
                                                                            Note, any long filenames must be surrounded in "double quotes". A CMD error is an error raised
   command < filename             Type a text file and pass the text        by the command processor itself rather than the program/command.
to command
                                                                            Redirection with > or 2> will overwrite any existing file.
   commandA    |   commandB       Pipe the output from commandA into
commandB                                                                    You can also redirect to a printer with > PRN or >LPT1

   commandA & commandB            Run commandA and then run commandB        To prevent the > and < characters from causing redirection, escape with a caret: ^> or ^<
   commandA && commandB           Run commandA, if it succeeds then         Examples of redirection:
run commandB                                                                    DIR >MyFileListing.txt
   commandA || commandB           Run commandA, if it fails then run
commandB                                                                        DIR /o:n >"Another list of Files.txt"

Numeric handles:                                                                ECHO y| DEL *.txt

STDIN = 0     Keyboard input                                                    ECHO Some text ^<html tag^> more text
STDOUT = 1    Text output
STDERR = 2    Error text output                                                 MEM /C >>MemLog.txt
UNDEFINED =   3-9
                                                                                Date /T >>MemLog.txt
   command 2> filename            Redirect any error message into a
file                                                                            SORT < MyTextFile.txt
   command 2>> filename           Append any error message into a
file                                                                            SET _output=%_missing% 2>nul
  (command)2> filename            Redirect any CMD.exe error into a
file                                                                            DIR C: >List_of_C.txt 2>errorlog.txt
   command > file 2>&1            Redirect errors and output to one
file                                                                            FIND /i "Jones" < names.txt >logfile.txt
   command > file 2<&1            Redirect output and errors to one
file                                                                            DIR C: >List_of_C.txt & DIR D: >List_of_D.txt
   command > fileA 2> fileB       Redirect output and errors to
separate files                                                                  ECHO DIR C: ^> c:logfile.txt >NewScript.cmd

   command 2>&1 >filename         This will fail!                               (TYPE logfile.txt >> newfile.txt) 2>nul

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


Windows Command Prompt                                   www.nubielab.com                                                                                           Page 64

More Related Content

PDF
Tool Development 08 - Windows Command Prompt
PPT
intro unix/linux 08
PPT
intro unix/linux 11
PPTX
PPT
intro unix/linux 07
PPTX
DOC
58518522 study-aix
ODP
intro unix/linux 02
Tool Development 08 - Windows Command Prompt
intro unix/linux 08
intro unix/linux 11
intro unix/linux 07
58518522 study-aix
intro unix/linux 02

What's hot (20)

PPT
intro unix/linux 06
PDF
4_Users_and_File_Permission_and_Directory_Commands
PDF
Operating system lab manual
PPT
intro unix/linux 09
PPT
intro unix/linux 10
PDF
Introduction to UNIX Command-Lines with examples
PDF
Os lab manual
PDF
basic-unix.pdf
PPT
8.1.intro unix
PDF
Unix practical file
PDF
Unix commands in etl testing
TXT
Applecmdlista zs
PPT
Internal commands.29to30
DOC
PC Software - Computer Application - Office Automation Tools
PPT
Basic Unix
PPT
intro unix/linux 04
PDF
Bozorgmeh os lab
PPTX
Know the UNIX Commands
PDF
Unix command line concepts
PPS
QSpiders - Unix Operating Systems and Commands
intro unix/linux 06
4_Users_and_File_Permission_and_Directory_Commands
Operating system lab manual
intro unix/linux 09
intro unix/linux 10
Introduction to UNIX Command-Lines with examples
Os lab manual
basic-unix.pdf
8.1.intro unix
Unix practical file
Unix commands in etl testing
Applecmdlista zs
Internal commands.29to30
PC Software - Computer Application - Office Automation Tools
Basic Unix
intro unix/linux 04
Bozorgmeh os lab
Know the UNIX Commands
Unix command line concepts
QSpiders - Unix Operating Systems and Commands
Ad

Viewers also liked (18)

PDF
Writing Modular Command-line Apps with App::Cmd
PPT
ATM Networking Concept
PPTX
Microsoft windows command prompt
PPTX
Introduction to computer network
PDF
Html advanced-reference-guide for creating web forms
PDF
Traceroute- A Networking Tool
PPTX
Introduction to Powershell Version 5
PDF
CMD in 2013
PPTX
12 Reasons Why Hot Entrepreneurs Fail
PPT
Tutorial visual aids ppt
PPTX
Fixing mobile phones
PPSX
Execute sql query or sql command sql server using command prompt
PDF
SyScan 2015 Bonus Slides - death of the vmsize=0 dyld trick
PPT
Excel Tutorial
PDF
Ip Networking Over Satelite Course Sampler
PPTX
Introduction to Processing and creative coding
DOC
CMD Command
PPTX
Programmable Logic Controller(PLC)
Writing Modular Command-line Apps with App::Cmd
ATM Networking Concept
Microsoft windows command prompt
Introduction to computer network
Html advanced-reference-guide for creating web forms
Traceroute- A Networking Tool
Introduction to Powershell Version 5
CMD in 2013
12 Reasons Why Hot Entrepreneurs Fail
Tutorial visual aids ppt
Fixing mobile phones
Execute sql query or sql command sql server using command prompt
SyScan 2015 Bonus Slides - death of the vmsize=0 dyld trick
Excel Tutorial
Ip Networking Over Satelite Course Sampler
Introduction to Processing and creative coding
CMD Command
Programmable Logic Controller(PLC)
Ad

Similar to Windows command prompt a to z (20)

PDF
Unix
PDF
Unix
PDF
PDF
Unix Commands Quick Guide
PDF
Doscommands
DOC
Some basic unix commands
PDF
Whats new in active directory window 2008 R2 server
PPT
Learning Linux v2.1
PDF
Windows command line_sheet_v1
PPT
1556 a 05
PDF
Introduction to Windows Dictionary Attacks
PPTX
Windows File Pseudonyms
PDF
Cheatsheet of msdos
PDF
Basic dos commands
PDF
Basic dos commands
PDF
Dos commands
DOC
Treebeard's Unix Cheat Sheet
PPT
Unix commands
Unix
Unix
Unix Commands Quick Guide
Doscommands
Some basic unix commands
Whats new in active directory window 2008 R2 server
Learning Linux v2.1
Windows command line_sheet_v1
1556 a 05
Introduction to Windows Dictionary Attacks
Windows File Pseudonyms
Cheatsheet of msdos
Basic dos commands
Basic dos commands
Dos commands
Treebeard's Unix Cheat Sheet
Unix commands

More from Subuh Kurniawan (6)

PDF
Windows 7 tricks
PDF
Konfigurasi mail server debian by subuh
DOCX
Instalasi ubuntu 11.04 dual boor with windows
PDF
Bagaimana prosesor dibuat
PDF
Instalasi ubuntu 11 single os non dual boot
PDF
Panduan instalasi clear os 5.2 standalone mode, web server, ftp server
Windows 7 tricks
Konfigurasi mail server debian by subuh
Instalasi ubuntu 11.04 dual boor with windows
Bagaimana prosesor dibuat
Instalasi ubuntu 11 single os non dual boot
Panduan instalasi clear os 5.2 standalone mode, web server, ftp server

Windows command prompt a to z

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