Windows command prompt a to z


Published on

  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Windows command prompt a to z

  1. 1. Windows Command Prompt Page 1
  2. 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 Page 2
  3. 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 ASSOC .ext=C:> arp -a -N [where .ext is the file extension].Add a static ARP cache entry on IP addr 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 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 Page 3
  4. 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 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 Page 4
  5. 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 Page 5
  6. 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 Page 6
  7. 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 Page 7
  8. 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 Page 8
  9. 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 Page 9
  10. 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 Page 10
  11. 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 Page 11
  12. 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 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. 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 Page 12
  13. 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 Page 13
  14. 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 Page 14
  15. 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 Page 15
  16. 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 Page 16
  17. 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 Page 17
  18. 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 Page 18