Your SlideShare is downloading. ×
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Windows command prompt a to z
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Windows command prompt a to z

1,258

Published on

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,258
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
124
Comments
0
Likes
2
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 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.SyntaxCreate Users: Password_options AddUsers /c filename [/s:x] [/?] Domain /p: - Set account creation options, used along withPassword_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 tokey 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 thedata. Syntax as follows: [Users] /s:x - Change the delimiter character used in filename User Name,Full name, Password, Description, HomeDrive, Homepath, Profile, Scriptto 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 Protocolgroups 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. SyntaxThe (: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 tableUnicode text format. Choosing to dump current user accounts does not save the accounts 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 hostscreate 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 entryname. ARP -d ip_addr [if_addr] CAUTION: Be careful when erasing user accounts,as it is not possible to recreateWindows 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 fileinterface 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 addressip_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 TypePhysical address is "jpegfile" given as 6 hexadecimal bytes separated byhyphens. 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 its 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 asbe modified. "image/jpeg" If not present, the first applicable interfacewill be used. The command ASSOC followed by just a file extension will display the current File Type forIf 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 hosts 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 othercomputer 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 associationC:> arp -a for that file typeDisplay 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 youC:> arp -s 10.1.4.77 00-AA-21-4A-2F-9A want to use.ASSOCDisplay 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.<fileWindows Command Prompt www.nubielab.com Page 3
  • 4. extension> /q : Quiet - Suppress interactive prompts.Therefore its possible to use registry permissions to protect a file extension and prevent any file /f : Force - Force overwrite or delete withoutassociation 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 .HTMLViewing file associations: The File extension is used by Windows NT to determine the type of information stored in the fileASSOC .txt and therefore which application(s) will be able to display the information in the file. FileASSOC .doc extensions are not case sensitive and are not limited to 3 characters.ASSOC >backup.txt Example: adding a File AssociationEditing file associations: To add the File Type "SQLfile"=Notepad.exe and also set the File Association ofASSOC .txt=txtfile .SQL="SQLfile" run this command:ASSOC .DIC=txtfileASSOC .html=Htmlfile ASSOCIATE .SQL Notepad.exeDeleting a file association: Example: Removing a File AssociationASSOC .html= ASSOCIATE .SQL /dRepair .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=regfileDigging 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 isapplication, 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 ONASSOCIATE.exe (Resource Kit) - : Clear an attribute OFFOne step file association. pathname : Drive and/or filename e.g. C:*.txtThis 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 wellFileType 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 TemporaryThe numeric values may be used when changing attributes with VBS/WSH The MSBACKUP, RESTORE, and XCOPY commands use these Archive attributes, as do manyIf 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 = 1Hidden and System attributes take priority. FILE_ATTRIBUTE_HIDDEN = 2 FILE_ATTRIBUTE_SYSTEM = 4If a file has both the Hidden and System attributes set, you can clear both attributes only with a FILE_ATTRIBUTE_DIRECTORY = 16single ATTRIB command. FILE_ATTRIBUTE_ARCHIVE = 32 FILE_ATTRIBUTE_ENCRYPTED = 64For example, to clear the Hidden and System attributes for the RECORD.TXT file, you would FILE_ATTRIBUTE_NORMAL = 128type: FILE_ATTRIBUTE_TEMPORARY = 256ATTRIB -S -H RECORD.TXT FILE_ATTRIBUTE_SPARSE_FILE = 512 FILE_ATTRIBUTE_REPARSE_POINT = 1024File Attributes FILE_ATTRIBUTE_COMPRESSED = 2048 FILE_ATTRIBUTE_OFFLINE = 4096You can use wildcards (? and *) with the filename parameter to display or change the attributes FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192for 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, Optionsyou must explicitly specify the directory name; you cannot use wildcards to work withdirectories. source The location of the Windows directory to use as theFor 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 thefolder, such as My Documents, Favorites, Fonts, etc. firmware.Setting the Read-Only attribute on a folder can affect performance, particularly on shared drivesWindows 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 whenloader object within Windows wont 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 OSExamplesInitialize 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 onlyC:> bcdboot C:Windows available from the recovery consoleSet the default BCD locale to Japanese, and copy BCD (Boot Configuration Data) files to drive Default identification strings:S: OS Load Options = /FastdetectC:> bcdboot C:Windows /l ja-jp /s S: Load Identifier = Microsoft Windows XP ProfessionalMerge 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.iniC:> bcdboot c:windows /m {d58d10c6-df53-11dc-878f-00064f4f4e08} DEL C:Boot.ini Bootcfg /RebuildBOOTCFG.exe FixbootEdit the Windows boot settings stored in Boot.iniSyntax 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 itinstance. normally inherits ACLs 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 userWindows Command Prompt www.nubielab.com Page 6
  • 7. Revoke specified users 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 inheritanceIn 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 currentspecify multiple files. file/directoryIf 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 FCacls 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 files 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 ACLs - 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":FWindows 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 OFFCALL SETLOCALCall one batch program from another. CALL :s_staff SMITH 100Syntax 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 :eofKey: :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 examplevariables in the argument @ECHO offCALL a second batch file SETLOCALThe CALL command will launch a new batch file context along with any specified arguments. set server1=frodo3When the end of the second batch file is reached (or if EXIT is used), control will return to just set server2=gandalf4after the initial CALL statement. set server3=ascom5CALL a subroutine (:label) set server4=last1The CALL command will pass control to the statement after the label specified along with anyspecified arguments . ::run the Loop for each of the serversTo exit the subroutine specify GOTO:eof this will transfer control to the end of the current call :loop server1subroutine. call :loop server2Arguments can be passed either as a simple string or using a variable: call :loop server3CALL MyScript.cmd "1234" call :loop server4CALL OtherScript.cmd %_MyVariable% goto:eofUse a label to CALL a subroutine :loop set _var=%1A label is defined by a single colon followed by a name. This is the basis of a batch file function. :: Evaluate the server nameCALL :s_display_result 123 CALL SET _result=%%%_var%%%ECHO Done echo The server name is %_result%GOTO :eof goto :eof:s_display_resultECHO The result is %1 :s_next_bitGOTO :eof :: continue belowWindows 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 javasubstitutions) C:windowsjava>If you CALL an executable or resource kit utility make sure its available on the machine wherethe 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:CDChange 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 REGEDIT4ROOT folder... [HKEY_CURRENT_USERSoftwareMicrosoftCommand Processor] C:windows> CD windowsjava "CompletionChar"=dword:00000009 C:windowsjava> Changing the Current driveWindows 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 /FTo change drive and directory at the same time, use CD with the /D switchC:> cd /D E:utils If the drive is the boot partition, you will be prompted to run the check during the next bootE: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 aCheck 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 fileshandles. 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 youthe 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 volumes masterfile 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 compressionfunctions are available. /T : Change the Autochk.exe initiation countdown time (timeExit codes in seconds) If you dont specify Time: displays the current0 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 drivesNotes: areConsider 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 aredetermined 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 XPWhen CHKDSK is set to run at boot-up there is a delay to allow the check to be cancelled - thiscan be configured in the registry:HKLMSystemCurrentControlSetControlSession ManagerREG_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 YNCHKNTFS.exe /N : Do not display choiceKeys at end of promptCheck 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 promptinvocations. 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. Ifavailable Password is not supplied, it will be requested.ERRORLEVEL will return the numerical offset of choiceKeys. /delete: Delete a user name and password from theAvailability list.Choice.com was originally supplied on the Windows 95 install CD, however there are some If TargetName is specified, that entry willissues with this version under NT - multiple concurrent invocations of CHOICE will clobber be deleted.each other. CHOICE.com will also burn a lot of CPUs when in a wait state. If /ras is specified, the stored remoteThe 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 storedIF 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 /listCMDKEY.exe (Windows 7) Add a user name and password for user Kate to access computer Server01 with the passwordCreate, 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 /rasKey: 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 entrywill 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 = BlackWindows 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 comparisonB = Light Aqua Running COMP with no parameters will result in a prompt for the 2 files and any options4 = 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 individual5 = 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 = YellowE = Light Yellow COMP will normally finish with a Compare more files (Y/N) prompt to suppress this: ECHO n|COMP <options>7 = WhiteF = Bright WhiteIf 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 SyntaxColour 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 switchThe 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 COLORcommand 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 creatingKey a destination file. This may be necessary when pathname1 The path and filename of the first file(s) copying between disksWindows 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 isinterrupted 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 fileNT 4 will overwrite destination files without any prompt, Windows 2000 and above will promptunless the COPY command is being executed from within a batch script. DELTo force the overwriting of destination files under both NT4 and Windows2000 use the Delete one or more files.COPYCMD environment variable: SyntaxSET COPYCMD=/Y DEL [options] [/A:file_attributes] files_to_deleteThis will turn off the prompt in Win2000 and will be ignored by NT4 (which overwrites by Keydefault) files_to_delete : This may be a filename, a list of files orBinary copies a Wildcard"COPY /B ... " will copy all the files in binary mode , you can also put /B after any one file tocopy 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_attributesworkaround for this is COPY null + file1 + file2 dest1COPY will accept UNC pathnames file_attributes:Copy from the console (accept user input) R Read-only -R NOT Read-onlyCOPY CON filename.txt S System -S NOT SystemThen type the input text followed by ^Z (Control key & Z) H Hidden -H NOT HiddenTo do this in Powershell use the following function: A Archive -A NOT Archivefunction copycon {[system.console]::in.readtoend() Wildcards: These can be combined with part of a filename}Examples: * Match any characters ? Match any ONE characterIn the current folder Examples:COPY oldfile.doc newfile.doc To delete HelloWorld.TXTCopy from a different folder/directory: DEL HelloWorld.TXTWindows 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 XPDEL A* Close all applications Open a command promptTo delete all files that end with the letter A Click Start, and then Shut DownDEL *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 theDEL *.DOC folder (DEL /s) At the command prompt, type explorer, and then press ENTER.To delete all read only filesDEL /a:R * DELTREETo delete all files including any that are read onlyDEL /F * Previous versions of Windows had the DELTREE command that deletes all files and sub folders. DEL /s will delete all filesFolders RD /s will remove all files and folders including the root folder. :: Remove all files and subfolders but NOT the root folderIf 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.comitself will not be removed. @echo off pushd %1Temporary 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 popdstructure 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 DELtoo - they dont use much space and constantly deleting and recreating them can potentiallyincrease 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.txtDEL C:examplesMyFile.txt KeyUndeletable 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:somedirLPT1Alternatively SUBST a drive letter to the folder containing the file. /P Prompts for confirmation before deleting eachIf 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 CreationExample: /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 dont 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 beChecking 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 anotherDisplay 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 displayType ECHO without parameters to display the current echo setting (ON or OFF). Examples: ::Sales.cmdIn most batch files you will want ECHO OFF, turning it ON can be useful when debugging aproblematic batch script. @Echo off SETLOCALIn a batch file, the @ symbol is the same as ECHO OFF applied to the current line only. Set _item="Ice Cream Maker" Set _price=450Normally 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.cmdCommand characters will normally take precedence over the ECHO statement @Echo offe.g. The redirection and pipe characters: & < > | ON OFF SETLOCAL CALL Sales.cmdTo 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 HolidayEcho text into a FILE @Echo off SETLOCALThe general syntax is CALL sub_productsEcho This is some Text > FileName.txt Echo [%_return1%] will cost [%_return2%]ENDLOCAL :sub_products SETLOCALWindows 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% :setErrorMultiple SET commands may be added to pass multiple variables, just prefix each with an & exit /B 5Be 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 :setErrorThe ENDLOCAL & SET technique described above can become difficult to read if you have a exit /B %1lot of SET commands all on the same line. This can be made easier to read if you first store allthe Set assignments in a single variable (_returns) as shown below (thanks to Ilya Bobyr for thistechnique)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 SourceEndlocal & %_returns%In these examples we have used the variable names _return1, _return2 etc, but you can use any Optionsnames for the return variables, even re-use the exact same variable name inside and outside theENDLOCAL command (SET _price=%_price%) Source : Source filename or a wildcardEXIT Destination : Destination filename or folderQuit the current batch script, quit the current subroutine or quit the command processor(CMD.EXE) optionally setting an errorlevel code. -r : Rename the filesSyntax EXPAND EXIT [/B] [exitCode] Uncompress one or more compressed files. SyntaxKey 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 cabinetYou should never attempt to directly write to the %errorlevel% variable, (i.e. dont try anything Wild cards (*.*) (.) and multiple files are validlike SET errorlevel...) using the EXIT command provides a safe way to alter the value of thebuilt-in errorlevel variable. optionsExamples /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 willIf not exist MyimportantFile.txt Exit /b copy from DMF disksEcho The file was found:: Set the error level to 5 /D Display CAB directory@echo offcall :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.execurrent 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_differentFC.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 followsSyntax FC /B pathname1 pathname2 1: different 2: same FC [options] pathname1 pathname2 3: same 4: differentKey /B : Perform a binary comparison. Specifying /nnnn =2 the file compare will display the 4th line and continueoptions 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 amaximum number /N : Display Line numbers. of mismatches after which the File Comparison willabort (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 matchafter 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 fromfiles 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) forcomparison. 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, EdinburghWindows 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 willTYPE names.txt | FIND "Jones" show show lines that contains any one word - (an OR of each word) - this behaviour is reversedYou 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 stringFOR %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 characterFINDSTR * Repeat: zero or more occurances of previous characterSearch for strings in files. or classSyntax FINDSTR [options] [/F:file] [/C:string] [/G:file] ^ Line position: beginning of line[string(s)] [pathname(s)] $ Line position: end of lineKey [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 forconsole). x Escape: literal use of metacharacter x /F:file Get a list of pathname(s) from a file (/ standsfor 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 ofoptions 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 commandWindows 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 thenTo 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.txtFINDSTR /s /i smith *.* Errorlevel When an item is not found FINDSTR will return an errorlevel >0Note 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 charactersTo 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 BugsFINDSTR /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 delimitersTo 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) DONow assume you want to find not only the word "computer", but also any other words that begin commandwith the letters comp, such as "computerise" or "compete" FOR /F ["options"] %%parameter IN ("Text string toFINDSTR "<comp.*" MyFile.txt process") DO commandExample of a literal search Key options:Searching a text file that contains the following delims=xxx The delimiter character(s) (default = athe quick brown fox space)the darkbrown foxthe really *brown* fox skip=n A number of lines to skip at the beginning ofFINDSTR /r .*brown MyFile.txt the file.or (default = 0)FINDSTR .*brown MyFile.txtWill both match the word "brown" in all 3 lines eol=; Character at the start of each line to indicate a commentFINDSTR /L *brown* MyFile.txt The default is a semicolon ;Will only match the last string tokens=n Specifies which numbered items to read fromUsing 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 namesWhen 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 dont specify delims it will default to "delims=<tab><space>" (useful if the text string contains doublequotes) 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 usebackqused. 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 dont expect to ever be in the data file e.g. "eol=€" orFOR /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 Examplesexecuted with the parameter(s) set to the token(s) found. Extracting data from this text file: January,Snowy,02By default, /F breaks up the line at each blank space " ", and any blank lines are skipped, this February,Rainy,15default parsing behavior can be changed by applying one or more of the "options" parameters. March,Sunny,25The 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 %%HEnableDelayedExpansion The tricky part is splitting up each the line into the right tokens, in this case Im splitting on theTokens comma character , this splits the line into 3 chunks of text and we pull out the first and thirdtokens=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> %%Htokens=* will cause all items on each line to be processed January 02tokens=3* will cause the 3rd and all subsequent items on each line to be processed February 15 March 25Each 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 toIf 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 fromDelims within another FOR statement you can refer to both sets of parameters. You cannot have moreMore 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 beenclosed 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 stringFOR /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 lineParse 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 aParse the contents of a file: time and then breaking the line up into individual items of data or tokens. The DO command isFOR /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") DOECHO %%G The FOR command is the answer to innumerable questions where you want to take the output ofFilenameset 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 varyLoop 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 isDO command [%%G] The tricky part is always splitting up the line of interest into the right tokens, in this case ImKey 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 usebackqindicate 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 processedquotes` 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 processedisWindows 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 inEach 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 allocatedfor 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-Filescan be broken up using "delims=;+". FOR %%parameter IN (set) DO commandYou can use any character as a delimiter, but they are case sensitive.If you dont specify delims it will default to "delims=<tab><space>" syntax-FOR-Files-Rooted at Path FOR /R [[drive:]path] %%parameter IN (set) DO commandNotice that some text editors will enter the TAB character as a series of spaces, specifying morethan one delimiter has been known to cause problems with some data sets. syntax-FOR-Folderseol FOR /D %%parameter IN (folder_set) DO commandThe default end-of-line character is a semicolon ; when the FOR command reads a text file (oreven a character string), any line that STARTS with the eol character will be ignored. In other syntax-FOR-List of numberswords it is treated as a comment. FOR /L %%parameter IN (start,step,end) DO commandUse 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 contentsin theory "eol=" should turn this feature off, but in practice this fails to work correctly so instead FOR /F ["options"] %%parameter IN (filenameset) DOset eol to some unusual character that you dont 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 commandTo ECHO from the command line, the name of every environment variable. FOR /F "delims==" %G IN (SET) DO @Echo %G syntax-FOR-Command ResultsThe 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 commandTo 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, specifyList 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 %%GIn 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 valuecommand.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 withIf 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 %%Jwill result in the output KeyThis 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 beEnvironment variables within a FOR loop are expanded at the beginning of the loop and wont used in thechange 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 greaterSET 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 dateiteration, using the CALL :subroutine mechanism: greater than@echo off or equal to (+) the current date plus "dd" days,SET count=1 orFOR /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:ProgramFiles" 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 stronglyIf 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 ExampleExamples: @echo offPrint 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 /xDelete the testfile if it is is 5 days old or older:C:> forfiles /m testfile.txt /c "cmd /c Del testfile.txt " /d -5Find .xls file that were last modified 30 days ago or longerC:> 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 programList the size of all .doc files: SyntaxC:> FORFILES /S /M *.doc /C "cmd /c echo @fsize" FTYPE fileType=executable_path FTYPEFORMAT.comFormat a disk for use with Windows. FTYPE fileTypeSyntax FORMAT drive: [/FS:file-system] [/V:label] [/Q] [size] FTYPE fileType=[/C] KeyKey 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 anyfloppy 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 howeverWindows 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 applicationsDocument"and "jpegfile" is displayed as "image/jpeg" If you have multiple applications that use the same file extension, the ASSOC command can beSeveral 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 FileTypejpegfile. Specify executable_path=nothing and the FTYPE command will delete the executable_pathFTYPE 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 FileTypesopened not only is the relevant application loaded into memory but the document itself alsoloaded into the application. To make this happen the filename of the document must be passed FTYPE >backup_types.txtback to the application. ASSOC >backup_ext.txtCommand line parameters are exactly like batch file parameters, %0 is the executable program Restore your FileTypes from a Backupand %1 will reference the document filename FOR /F "tokens=* delims=" %G IN (backup_types.txt) DO FTYPE %Gso a simple command line might be: FOR /F "tokens=* delims=" %G IN (backup_ext.txt) DO ASSOC %GMyApplication.exe "%1" This will recreate the CLASS ids in the registry at HKey_Classes_Root.<file extension> If you put the commands above in a batch file change the %G to be %%GIf any further parameters are required by the application they can be passed as %2, %3. To passALL parameters to an application use %*. To pass all the remaining parameters starting with the Using File associations at the command linenth 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 promptThe 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.DOCASSOC .html=htmlfileFTYPE 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" SyntaxASSOC .rtf=rtffile GOTO labelFTYPE word.rtf.8="C:Program FilesMicrosoft OfficeOfficewinword.exe" /n KeyASSOC .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 12goto: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 12goto: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 Keybatch /T Traverse all subfolders to match files/directories.@echo offsetlocal /C Continue on file errors (access denied) Error messagesIF /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??..." - XKCDiCACLS.exe (2003 sp2, Vista) /grant :r user:permissionChange file and folder permissions - display or modify Access Control Lists (ACLs) for files and Grant access rights, with :r, the permissionsfolders. 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 inheritprecede the level: (CI) - container inherit /inheritance:e|d|r (IO) - inherit only e - enable inheritance (NP) - dont 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 grantsdirectory 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 ACLs 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 files 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 files owner) R - read-only access  File "Ownership" will always override all ACLs - 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 syntaxSo 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 commandWhen 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 Syntaxreturns “Access denied”. IF [NOT] DEFINED variable commandA limited release hotfix is available to resolve this issue (Q947870) alternatively useSUBINACL IF [NOT] ERRORLEVEL number commandnb this bug is NOT present on Vista SP1 or Windows Server 2008.Examples: IF CMDEXTVERSION number commandTo backup the ACLs of every file in a directory type: keyicacls * /save Myacl_backup.txt item May be a text string or an environment variableRestore ACLS using a previously saved acl file: a variable may be modified using eithericacls /restore Myacl_backup.txt Substring syntax or Search syntaxChange the Integrity Level (IL) of a file to High: command The command to performicacls 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 wont 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 operatorsFile 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 exampleNote some errors are negative numbers. the command below will fail:When working with errorlevels in a batch file its 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 valuesExamples: Do not use brackets or quotes when comparing numeric valuesIF 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 commandIF 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 exactlyIF %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, GEQTo test for the existence of a command line parameter - use empty brackets like this when comparing numbers as a string "026" > "26" WildcardsIF [%1]==[] ECHO Value Missing Wildcards are not supported by IF, so %COMPUTERNAME%==SS6* will not match SS64orIF [%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_matchedaltogether, so testing for NULLs becomes easy: Pipes When piping commands, the expression is evaluated from left to right, soIF 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) ERRORLEVELTest 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% (userthe folder is empty or not. variable) if present such a variable will prevent the real ERRORLEVEL (a system variable) from beingBrackets used by commands such as ECHO and IF. To test for the existence of a user variable use SET errorlevel, or IF DEFINED ERRORLEVELYou 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 ERRORLEVELe.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 itsIPCONFIG name starting with ELConfigure IP (internet protocol configuration) > ipconfig /release *Con* ... release all matchingSyntax 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 specifiedadapter. > 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 = TESTadapter. 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_idDNS names. KILL [option] task_name KILL [option] window_title IPCONFIG /displaydns Display the contents of the DNS ResolverCache. 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 hadnt committed to disk yet. It is there for worst casefor adapter. scenarios - when you absolutely must end the process now, and dont 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 aIf 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 belowThe default is to display only the IP address, subnet mask and default gateway for each adapterbound 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 Syntaxadapters bound to TCP/IP will be released or renewed. LOGOFF [/f] [/n]For Setclassid, if no ClassId is specified, then the ClassId is removed. KeyExamples: /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. ExamplesWindows security log events mapisend -u "MS Exchange Settings" -p MyPassword -rLogon Event IDs 528 and 540 = successful logon billg@sun.com -s "Subject" -m "Test message text"Logoff Event ID 538 = logoffLogon and logoff events also specify a Logon Type code: mapisend -u "MS Exchange Settings" -p MyPassword -r billg@hp.comLogon Type 2 – Interactive - Log on at the local keyboard / screen (see the event description for -s "Subject" -t c:MyMail.txt >> c:mail.loga 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 MEMwas 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 Syntaxlogon type 2. MEMLogon Type 10 – RemoteInteractive - Terminal Services, Remote Desktop or Remote MEM /CAssistance. MEM /DLogon Type 11 – CachedInteractive - mobile users not connected to the network connecting with MEM /Pcached credentials. Key /P List programs in memoryMAPISEND (Back Office/Exchange Resource kit) with the memory address and size of eachSend 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 wont 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 Syntaxmessage) MD [drive:]path"profile" is the profile name (user mailbox) of sender Key"subject" is the subject lineWindows Command Prompt www.nubielab.com Page 33
  • 34. The path can consist of any valid characters up to themaximum path length available MKDIR is a synonym for MDYou should avoid using the following characters in folder names - they are known to causeproblems© ® " - & ^ ( ) and @ MOVE Move a file from one folder to anotheralso 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 Keycharacters. 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 MyFolderMake 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 theC: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 earlyMake an entire path versions of windows (e.g. NT4) which dont 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.docfor 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.wpYou 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 >nulIf you plan to copy data onto CDROM avoid folder trees more than 8 folders deepWindows Command Prompt www.nubielab.com Page 34
  • 35. allows in-use files to be replacedMSG.exeSend 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 aSyntax 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 iscurrent). 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 willMove File - Copy a file to another location even if the file is in use (Locked) be deleted from the registrySyntax MV /x /d source destinationKey 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 timeWindows Command Prompt www.nubielab.com Page 35
  • 36. KeyThe contexts and commands available vary by platform, the list netsh advfirewall monitor delete - Delete all matchingbelow is for Windows 2008. security associations.Use interactive mode/help (described below) to check the netsh advfirewall monitor dump - Display acommands 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 allnetsh advfirewall consec ? - Display a list of profiles.commands. netsh advfirewall set currentprofile - Set properties in thenetsh advfirewall consec add - Add a new connection active profile.security rule. netsh advfirewall set domainprofile - Set properties in thenetsh advfirewall consec delete - Delete all matching domain profile.connection security rules. netsh advfirewall set global - Set the globalnetsh advfirewall consec dump - Display a properties.configuration script. netsh advfirewall set privateprofile - Set properties in thenetsh advfirewall consec set - Set new values for private profile.properties of an existing rule. netsh advfirewall set publicprofile - Set properties in thenetsh advfirewall consec show - Display a specified public profile.connection security rule. netsh advfirewall show allprofiles - Display properties fornetsh 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 globalpolicy to the specified file. properties.netsh advfirewall import pathfilename - Import policy from the netsh advfirewall show privateprofile - Display properties forspecified file. the private profile. netsh advfirewall show publicprofile - Display properties fornetsh advfirewall firewall add - Add a new inbound or the public profile.outbound firewall rule. netsh advfirewall show store - Display the policy storenetsh 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 componentproperties 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 operationalto 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 servicenetsh delete helper Remove the specified helper DLL from configuration.netsh. netsh firewall show allowedprogram - Show firewall allowedNote 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 firewallnetsh dhcpclient list - List all the commands profile.available. netsh firewall show icmpsetting - Show firewall ICMPnetsh dhcpclient trace enable - Enable tracing for DHCP configuration.client and DHCP QEC. netsh firewall show logging - Show firewall loggingnetsh 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 notificationnetsh 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 serviceexec - 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 helpnetsh firewall dump - Display a configurationscript. =http - Change to the netsh http context.netsh firewall reset - Reset firewall configuration netsh http add - Add a configuration entry to ato default. table.netsh firewall set allowedprogram - Set firewall allowed program netsh http delete - Delete a configuration entry from aconfiguration. 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 interfacenetsh 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 atable. file to the policy store.netsh interface delete - Delete a configuration entry netsh ipsec static set - Modify existing policies andfrom a table. related information.netsh interface dump - Display a configuration script. netsh ipsec static show - Display details of policiesnetsh 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 aisatap 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 interfacetcp context. =nap - Change to the netsh nap context.netsh interface teredo + Change to the netsh interface netsh nap client + Change to the netsh nap clientteredo 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 statenetsh ipsec dump - Display a configuration script. information.netsh ipsec dynamic add - Add policy, filter, andactions 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 aactions from SPD. table.netsh ipsec dynamic dump - Display a configuration netsh netio delete - Delete a configuration entry from ascript. 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, andactions from SPD. =ras - Change to the netsh ras context. (Remotenetsh ipsec static add - Create new policies and Access Server)related information. netsh ras aaaa - Change to the netsh ras aaaanetsh 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 diagnosticsnetsh 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 modenetsh 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 isnetsh rpc delete - Create a Delete list of subnets. an alias for dnsserver, ip is an alias for ipv4netsh 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.dllnetsh rpc reset - Reset the selective binding settingsto 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 configmachine.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=1If 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 DHCPmachine. 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.1netsh 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.2netsh winhttp reset - Reset WinHTTP settings. register=nonenetsh 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 LSPsthat 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=staticnetsh winsock remove - Remove a Winsock LSP from the addr=192.168.100.3system.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=dhcpWindows Command Prompt www.nubielab.com Page 39
  • 40. -S (Sessions) List sessions table with the destinationBackup the local DHCP server configuration to a file: IP addressesC:> netsh dump dhcp > C:backupDHCPconfig.dat -s (sessions) List sessions table convertingYou 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 andC:> netsh set machine server64 then, starts RefreshBackup the current network interface configuration to a file: interval Redisplay selected statistics, pausingC:> netsh dump interface > c:backupInterfaceConfig.dat interval seconds between each display. Press Ctrl+C toRestore network interface configuration from a file: stop redisplayingC:> netsh exec c:backupInterfaceConfig.dat statistics.Run Netsh from Powershell (returns a Text object you can manipulate)PS C:> $myFWstate=netsh firewall show statePS C:> $myFWstate -match "disable"Disable Network auto-tuning (certain routers and networking devices perform better with thisoff.)PS C:> netsh interface tcp set global autotuning=disabledEnable Network auto-tuning (certain routers and networking devices perform better with thison.)PS C:> netsh interface tcp set global autotuning=normal NETSTAT.exeNBTSTAT.exe Display current TCP/IP network connections and protocol statistics.Display protocol statistics and current TCP/IP connections using NBT (NetBIOS over TCP/IP). SyntaxSyntax 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 machines name table connection.given its name -A (Adapter status) List the remote machines name table -b Display the exe involved in creating each connection orgiven its IP address listening port.* -c (cache) List NBTs cache of remote [machine] -v Verbose - use in conjunction with -b, to display thenames 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 protocolWINS 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 protocolsWindows 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 currentare default host shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and MyHost - print ip address of MyHostUDPv6; 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 infothese. set [no]d2 - print exhaustive debugging info interval Redisplay statistics, pausing interval seconds set domain=NAME - set default domain name to NAMEbetween set root=NAME - set root server to NAME each display. (default=once only) Press CTRL+C root - set current default server to the rootto stop. server NAME - set default server to NAME, using current* Where available this will display the sequence of components involved in creating the default serverconnection or listening port. (Typically well-known executables which host multiple independent lserver NAME - set default server to NAME, using initialcomponents.) This option will display the executable name in [ ] at the bottom, with the servercomponent 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 listconsuming 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 circuitNSLOOKUP (TCP/IP) set class=X - set query class (for example, INLookup 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 SeAuditPrivilegeExample: Manage auditing and security log SeSecurityPrivilegeC:> nslookup -querytype=TXT -timeout=10 porttest.dns-oarc.net Backup files and directories SeBackupPrivilege Add workstations to the domain SeMachineAccountPrivilege Shut down the system SeShutdownPrivilegeNTRIGHTS.exe (Resource Kit, 2000/2003) Force shutdown from a remote system SeRemoteShutdownPrivilegeEdit user account Privileges. Create a pagefile SeCreatePagefilePrivilegeSyntax Increase quotas SeIncreaseQuotaPrivilege NTRIGHTS +r Right -u UserOrGroup [-m Computer] [-e Restore files and directories SeRestorePrivilegeEntry] 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 accountsKey: to be trusted for delegation SeEnableDelegationPrivilege +/-r Right Grant or revoke one of the rights listed Remove computer from docking station SeUndockPrivilegebelow. Service Privileges: Create permanent shared objects SeCreatePermanentPrivilege -u UserOrGroup Who the rights are to be granted or revoked Create a token object SeCreateTokenPrivilegeto. 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 computers Profile a single processevent log. SeProfileSingleProcessPrivilegeBelow are the Privileges that can be granted or revoked, all are Case-Sensitive. Load and unload device drivers SeLoadDriverPrivilegeLogon 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 SeSystemEnvironmentPrivilegeSeNetworkLogonRight Profile system performance SeSystemProfilePrivilege Deny Access to this computer from the network Obsolete and unused SeUnsolicitedInputPrivilegeSeDenyNetworkLogonRight (has no effect) Allow logon through Terminal Services To run ntrights you need to be an administrator, to change privileges remotely (-m option) youSeRemoteInteractiveLogonRight (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 grantSeDenyRemoteInteractiveLogonRight (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 numericAllow all members of the local Users group to logon locally OpenFileID on computerntrights -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 openthis security change in the event log: files on computer.ntrights -u MyDomAdmin_RDP +r SeRemoteInteractiveLogonRight -m server64 -e "AddedRDP rights for Admin_RDP" /a Disconnect all open files that were accessed by userAllow all members of the domain group Admin_General to shutdown this computer. on computer. The wildcard (*) can be used to disconnect all openntrights -u MyDomAdmin_General +r SeShutdownPrivilege files on computer.Allow the domain user JDoe to shutdown the machine Server64ntrights -u MyDomJDoe +r SeShutdownPrivilege -m Server64 /o Disconnect all open files with the specified OpenModeSpecifically 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]} [/seSessionName] [/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 touse 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 /vare TABLE, LIST, and CSV. Default=TABLE. C:> openfiles /query /s Server64 /u SS64DomFileAdmin /p password1Windows Command Prompt www.nubielab.com Page 43
  • 44. FirewallsPS C:> openfiles /disconnect /id 1 Like tracert PathPing uses Internet Control Message Protocol (ICMP) over TCP/IP. ManyPS 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 byC:> openfiles /disconnect /op "c:workfinance.xls" causing traffic to flow via a path you didnt 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. SyntaxPATHPING PERMS [account] [path] optionsTrace route and provide network latency and packet loss for each router and link in the path.Combines the functionality of PING and TRACERT. KeySyntax 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 prioritytags. 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 networkproblems - it displays the degree of packet loss at any given router or link. D Delete file or folder. May be inherited from the parentPathping sends multiple Echo Request messages to each router between a source and destination folderover 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 Allmultiple pings can be sent in parallel. Its therefore possible to choose a Timeout parameter that isless than the wait Period * Number of hops. - No AccessWindows 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 600Syntax 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_hostKey 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 Dont 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 theProcessor. 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% == 0options. 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 mayprompting. 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. valuePING IP_address_of_local_host REG ADD [ROOT]RegKey /v ValueName [/t DataType] [/S3) 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 thePING IP_address_of_default_gateway (default) value4) 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 underExamples this keyPING -n 1 -w 7500 Server_06 REG COPY [SourceMachine][ROOT]RegKeyPING -w 7500 MyHost |find "TTL=" && ECHO MyHost found [DestMachine][ROOT]RegKeyPING -w 7500 MyHost |find "TTL=" || ECHO MyHost not found REG EXPORT [ROOT]RegKey FileName.reg REG IMPORT FileName.regPING -n 5 -w 7500 www.microsoft.com REG SAVE [ROOT]RegKey FileName.hiv REG RESTORE MachineName[ROOT]KeyName FileName.hivPING -n 5 -w 7500 microsoft.comScript to monitor your connection to a website (example.com) every 15 seconds: REG LOAD FileName KeyName@Echo off REG UNLOAD KeyNameEcho 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>nulgoto start Key:The script above can be used to test an Internet connection, just replace example.com with your ROOT :ISPs Default Gateway IP address. This represents the first physical device on the ISPs side of HKLM = HKey_Local_machine (default)your connection. You can find the Default Gateway on your router status screen. HKCU = HKey_current_userNote: some ISP’s or network admins may not appreciate you performing frequent or continual HKU = HKey_userspings to their server, try not to overdo it! HKCR = HKey_classes_rootPING 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", integerREG.exe etcRead, 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 HKCUSoftwareSS64overwrite Y/N" REG COPY HKCUSoftwareSS64 HKCUSoftwareSS64Copy Machine : Name of remote machine - omitting defaults to REG EXPORT HKCUSoftwareSS64 C:MyReg.REGcurrent machine. REG IMPORT C:MyReg.REG Only HKLM and HKU are available on remote REG SAVE HKCUSoftwareSS64 C:MyRegHive.hivmachines. 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 inREG_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 | SyntaxREG_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 scriptthe command line, assuming the Remote Registry Service is running. REGEDIT pathnameRegistry 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 importTo include a quote mark (") in the data, prefix it with the escape character () e.g. "Here is " a REGEDIT /S pathnamequote"Enclose ValueNames that contain the character in single quotes. Start the regedit GUIREG RESTORE has a tendency not to work, possibly due to firewall issues, Export and Import REGEDITare much more reliable.Examples Open multiple copies of GUI (XP and 2003 only)REG QUERY HKCUConsole REGEDIT -mREG QUERY HKCUConsole /v ScreenBufferSizeREG ADD HKCUSoftwareSS64 /v Sample /d "some test data" KeyREG QUERY HKCUSoftwareSS64 /v Sample /E : ExportREG ADD HKLMSoftwareDiLithium /v WarpSpeed /t REG_BINARY /d /S : Silent Importffffffff 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 Dont call DllRegisterServerWhen double clicking this .reg file the key and value will be added. /i Call DllInstall (or DllUninstall if /u isAlternatively 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 ExamplesCreate a reg file like this, notice the hyphen inside the first bracket Unregister (disable) XP Zip foldersWindows 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.dllbinary or Dword values in that key. Register (enable) XP Zip folders REGSVR32 zipfldr.dllIf 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.dlle.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.dllAgain double clicking this .reg file will delete the values specified, or you can use REGEDIT /s regsvr32 /s wucltui.dllMyDeleteScript.REG regsvr32 /s wups2.dll regsvr32 /s wups.dllCompare the Registry of two machines regsvr32 /s wuweb.dllWindiff 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.) SyntaxREGSVR32 REGINI [-m machinename | -h hivefile hiveroot | -wRegister 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 windowif 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 values 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 ofREGINI 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 numbersstrings 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 Accessline 3 - Administrators Read and Write Access continuations after the first number that gave the 4 - Administrators Read, Write and Delete Accesssize of the data. 5 - Creator Full Access It just kept looking on following lines until it 6 - Creator Read and Write Accessfound enough data 7 - World Full Access values to equal the data length or hit invalid input. 8 - World Read AccessQuoted 9 - World Read and Write Access strings were only allowed in REG_MULTI_SZ. They 10 - World Read, Write and Delete Accesscould not be 11 - Power Users Full Access specified around key or value names, or around values 12 - Power Users Read and Write Accessfor REG_SZ or 13 - Power Users Read, Write and Delete Access REG_EXPAND_SZ Finally, the old REGINI did not 14 - System Operators Full Accesssupport 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 Accessregistry data. 18 - System Read and Write AccessThe easiest way to understand the format of the input textFile is to use the REGDMP command 19 - System Read Accesswith no arguments to dump the current contents of 20 - Administrators Read, Write and Execute Accessyour NT Registry to standard out. Redirect standard out to a file and this file is acceptable as 21 - Interactive User Full Accessinput to REGINI 22 - Interactive User Read and Write Access 23 - Interactive User Read, Write and DeleteSome general rules are: AccessSemicolon 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 takescharacter 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 keysBackslash 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 enoughLeading 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 numberdata 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 bytesis 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, theThe 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 cant create a value with leading or trailing spaces, an equal sign oran 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 beValid 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 RENREG_BINARY) REG_RESOURCE_REQUIREMENTS_LIST (same format as You cannot specify a different drive or path for `new_filename` - use the MOVE commandREG_BINARY) instead. REG_FULL_RESOURCE_DESCRIPTOR (same format asREG_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 ????.xyzIf 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 ourFor 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 andcan 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. REPLACEFor REG_MULTI_SZ, each component string is surrounded by quotes. If you want an imbedded Replace or update one file with anotherquote character, then double quote it, as in string2 above. SyntaxWindows 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.exeKey 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 thesource. 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] [MASKSyntax 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 gatewayKey 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_hostPlace 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 listingthe pathname to each. -p Create a persistent route - survives systeme.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 Examplesroute. 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 beNote 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. SyntaxSymbolic names used for Destination_Host are looked up in the network database file tasklist optionsNETWORKS. 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 computerIf the command is PRINT or DELETE. Destination or gateway can be a wildcard (*), or the dont 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 accountsays: When matching this pattern, dont worry about matching any of the bits - everythingmatches. /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 ordestination routes are printed. The * matches any string, and ? matches any one char. /vExamples:157.*.1 /m [ModuleName]157.* Show the processes that include the given127.* module.*224*SYSTEMINFO /v Verbose task informationList system configurationSyntax /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 LISTKey: 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 besession number. terminated. SessionName eq, ne String Status eq, ne RUNNING | /IM image name The image name of the process to beNOT RESPONDING terminated. CPUTime eq, ne, gt, lt, ge, le Time Wildcard * can be used to specifyhh:mm:ss all image names. MemUsage eq, ne, gt, lt, ge, le Any validinteger. /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 Positivetasklist /v /fi "STATUS eq running" integer. Session eq, ne, gt, lt, ge, le Any validtasklist /v /fi "username eq ORACLE_SERVICE_ACCOUNT" session number.WMIC can also list running processes and parameters: Status eq, ne RUNNING | NOTWMIC /OUTPUT:C:ProcList.txt PROCESS get RESPONDINGCaption,Commandline,Processid CPUTime eq, ne, gt, lt, ge, le Time hh:mm:ssTASKLIST MemUsage eq, ne, gt, lt, ge, le Any validEnd 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 StringOptions 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.exeomitted. 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.exeWindows 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*" FirewallsTRACERT Many firewalls will block ICMP traffic by default. If an attacker is able to forge ICMP redirectTrace 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 thelarge 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 didnt intend.intermediate systems (routers or bridges) are involved.Syntax Examples TRACERT [options] target_name TRACERT www.doubleclick.netKey TRACERT 123.45.67.89 target_name The HTTP or UNC name of the host TRACERT local_serverOptions: 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 fortarget.(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 forseparated 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 iscosmetically improved under XP. /T Traverse all subfolders and change all matchingTracert 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 torecord the route taken - but only if the particular network devices support it. /x Edit ACL instead of replacing it; affect only ACEsThis 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 routeralong 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-rideWhen 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 users rights without verifyor the maximum number of hops is reached. /P user:permision[;FolderSpec] Replace users rights. see /G option belowWindows 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 subfoldersFolderSpec is a permission applied to a folder. If FolderSpec is not specified then permission XCACLS MyFolder /T /E /G guests:fwill 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;TrFolderSpec = ;T@ where @ is one of the rights above, when this is specified new files willinherit 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 MyFolderexample ;TF will apply full control (but ;FT is not valid) XCACLS MyFolder /T /P guests:xWildcards can be used to specify more that one file in a command. You can specify more thanone 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 commandInheritance 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 thenewer iCACLS command instead of XCACLS. XCOPY is particularly useful when copying files from CDROM to a hard drive, as it willInherited folder permissions are displayed as: automatically remove the read-only attribute. OI - Object inherit - This folder and files. (no inheritance Syntaxto subfolders) XCOPY source [destination] [options] CI - Container inherit - This folder and subfolders. IO - Inherit only - The ACE does not apply to the current Keyfile/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 OptionsSo 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 partdestination. 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 namesfolders. 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 notpath 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 allfiles 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 archivingcopy. 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 ACLinformation. /X Copy file audit settings (implies /O).XCOPY will accept UNC pathnamesExamples:To copy a file: SyntaxXCOPY C:utilsMyFile D:BackupCopyFile ParametersTo 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 2468To copy a folder including all subfolders. You can get the value of any parameter using a % followed by its numerical position on the command line. The first item passed is always %1 the second item is always %2 and so onXCOPY 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 ExtensionsThe /i defines the destination as a folder. When a parameter is used to supply a filename then the following extended syntax can beNotes 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.txtCOPYCMD 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 bydefault). %~p1 - expands %1 to a Path only - utilsWhen 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) - theseconds for a FAT volume and 0.1 microsecond for an NTFS volume. last folder in that pathThe WinXP version of XCOPY will accept wildcards for the source e.g. *.txtIt 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 %1Windows 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 commandname of the first match found. FOR /F %%G IN (DIR /b *.*) DO call :s_subroutine %%GThe 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 andWhen writing batch scripts its 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=%~dp1This 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 characterA workaround is to run command.com /c rem , which will change the current directory to 8.3 long: %Ae.g. if the current directory is C:Program Files you will see the bugif 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 VariablesFOR command parameters Default value: Default value: VariableThe FOR command creates parameters which are identified with a letter rather than a number. Windows XP Windows 7/2008These are easily confused with the parameter modifier letters described above. C:Documents and SettingsAllTherefore when using FOR its best to avoid the letters (a, d, f, n, p, s, t, x, z), apart from making %ALLUSERSPROFILE% C:ProgramData Userscode 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 DataYou can get the pathname of the .CMD script itself with %0If 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 Filesmapped drive. FilesYou 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 Filesfolder as the batch script by using this syntax: %COMMONPROGRAMFILES(x86)% Files (x86)Common Files CALL %0..SecondBatch.cmdThis 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.exeExamples: d.exePass 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 anotherWindows 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.cmdAn 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 byExample 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: :myfunctLoops and subroutines SETLOCALThere 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% ENDLOCALFOR aaa DO xxx - will conditionally perform a command several times (for a set of data, or aset 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=%1If 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 dont have to worry if any variable names will clash. :s_page_on_c In other words you can do this: ECHO pagefile foundWindows 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 commandCALL :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 SyntaxSETLOCAL SET variableSET _var1=%1 SET variable=stringSET _var2="%_var1%--%_var1%--%_var1%" SET /A variable=expressionENDLOCAL & 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 Sume.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 scriptingIF 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 _departmentpart 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 allIF EXIST MyFile.txt (ECHO Some[more]Potatoes) matching variablesYou 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 pmisinterpreted by the command processor. Display variables that begin with an underscore SET _Testing Numeric values ExamplesDo not use brackets or quotes if you are comparing numeric values with an IF commande.g. Storing a text string:IF (2) GEQ (15) echo "bigger"or C:>SET _dept=Sales and MarketingWindows Command Prompt www.nubielab.com Page 61
  • 62. C:>set _ ECHO (%substring%)_dept=Sales and Marketing Deleting an environment variableOne variable can be based on another, but this is not dynamicE.g. Type SET with just the variable name and an equals sign:C:>set xx=fishC:>set msg=%xx% chips SET _department=C:>set msgmsg=fish chips Better still, to be sure there is no trailing space after the = use:C:>set xx=sausage (SET _department=)C:>set msg ormsg=fish chips SET "_department="C:>set msg=%xx% chipsC:>set msg Variable names can include Spacesmsg=sausage chipsAvoid 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 theas 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 " SimilarlyPrompt for user input SET _var =MyText@echo off will create a variable called "_var " - note trailing spaceSet /P _dept=Please enter Department:If "%_dept%"=="" goto :sub_error To avoid problems with extra spaces appearing in your output, issue SET statements inIf /i "%_dept%"=="finance" goto sub_finance parentheses, like thisIf /i "%_dept%"=="hr" goto sub_hrgoto:eof (SET _department=Some Text) Alternatively you can do:sub_finance SET "_department=Some Text"echo You chose the finance deptgoto:eof Note: if you wanted to actually include a bracket in the variable you need to use an escape character.:sub_hrecho You chose the hr dept The SET command will set ERRORLEVEL to 1 if the variable name is not found in the currentThe /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 commandThe 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 SetXSET /a calculations or in the GUI - Control Panel, System, Environment, System/User VariablesEnclose 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.bat16 } 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 wont 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 parsedallows 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=MyText0x for hexadecimal numbers, Redirection0 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 intocommandB 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 runcommandB DIR /o:n >"Another list of Files.txt"Numeric handles: ECHO y| DEL *.txtSTDIN = 0 Keyboard input ECHO Some text ^<html tag^> more textSTDOUT = 1 Text outputSTDERR = 2 Error text output MEM /C >>MemLog.txtUNDEFINED = 3-9 Date /T >>MemLog.txt command 2> filename Redirect any error message into afile SORT < MyTextFile.txt command 2>> filename Append any error message into afile SET _output=%_missing% 2>nul (command)2> filename Redirect any CMD.exe error into afile DIR C: >List_of_C.txt 2>errorlog.txt command > file 2>&1 Redirect errors and output to onefile FIND /i "Jones" < names.txt >logfile.txt command > file 2<&1 Redirect output and errors to onefile DIR C: >List_of_C.txt & DIR D: >List_of_D.txt command > fileA 2> fileB Redirect output and errors toseparate files ECHO DIR C: ^> c:logfile.txt >NewScript.cmd command 2>&1 >filename This will fail! (TYPE logfile.txt >> newfile.txt) 2>nulRedirect 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 butsuppress errorWindows Command Prompt www.nubielab.com Page 64

×