Windows Batch Learning---01

Source: Internet
Author: User
Tags create directory switch case alphanumeric characters

First, Mark symbol:

1 CR (0D) command line Terminator2 Escape (1B) ANSI escape character Guide3Space ( -) commonly used parameter specifiers4Tab ( the) ; =non-trivial parameter qualifiers5+Copy command file connector6* ?File wildcard characters7 ""string delimiter8|Command Pipe character9< > >>File redirection characterTen @ command-line Echo Mask One/parameter Switch guide character A : Batch Label guide -% Batch Variable guide

  ::Can actually play the role of REM annotation, and more concise and effective; But there are two points to note:

(1) In addition :: , any word in the : beginning of the lines, in the batch is regarded as the label, and directly ignore all subsequent content, just to distinguish with the normal marking, it is recommended to use goto unrecognized label, that is, : immediately after a non-alphanumeric special symbol.

(2) Unlike rem the :: following, the character lines is not echoed at execution time, regardless of whether the command-line Echo state is opened with Echo on, because the command interpreter does not consider him to be a valid command line, and for this point, REM will be more applicable than in some cases :: . In addition, REM can be used in Config.sys files.

Second, the parameters

A batch file can also use parameters (equivalent to command-line arguments of a DOS command) in the same way as a C-language function, which requires a parameter specifier % .

%[1-9]Represents a parameter, which is a string separated by a space (or tab) after the file name when the batch file is run. Variables can be from %0 to %9 , representing the %0 batch command itself, and other parameter strings are %1 represented in %9 order.

Example 2:C: The root directory has a batch of processing files named F.bat, the content is:

  @echo off  format%1

If executed C:\>f a: , then when executing the f.bat, it means that it is %1 a: equivalent, so the format %1 format a: above command is actually executed when it is run format a: .

Example 3: C: Root directory The next batch of processing file name is T.bat, content is:

  @echo off  type%1  type%2

Then runC:\>t a.txt b.txt

%1: Represents A.txt

%2: Represents B.txt

Third, control statements

if,,, goto choice for is a batch control statement command.

If statement

If is a conditional statement that determines whether a specified condition is met, thereby deciding to execute a different command. There are three types of formats:

IF [NOT] ERRORLEVEL number commandif [NOT] string1==string2 commandif [NOT] EXIST filename command
    • if [not] "参数" == "字符串" 待执行的命令

If the parameter equals (not equal to, the same as) the specified string, the condition is set, run the command, or run the next sentence.

Cases:if "%1"=="a" format a:

The description of this point in the IF command-line help is:IF [NOT] string1==string2 command

Here are some points to note:

    1. Double quotation marks that contain strings are not required by syntax, but rather an "anti-aircraft" character that is used habitually
    2. String1 is not necessarily a parameter, it can also be an environment variable, a loop variable, and other string constants or variables
    3. command is not required by syntax, string2 followed by a space to form a valid command line
    • if [not] exist [路径\]文件名 待执行的命令

If there is a specified file, then the condition is established, run the command, otherwise run the next sentence.

Such as:if exist c:\config.sys type c:\config.sys

Indicates that if a C:\Config.sys file exists, its contents are displayed.

You can also use the following usage:

If exist command

In a DOS system, a device is also considered a special file, and a file can also be called a character device; Because the device and the file are managed using a handle (handle), the handle is the name, similar to the file name, except that the handle is not applied to disk management, but is applied to memory management, and so-called device loading refers to allocating a reference handle to it in memory.
    • if errorlevel <数字> 待执行的命令

Many DOS programs return a numeric value at the end of the run to indicate the result (or state) of the program's operation, and the IF ERRORLEVEL command can determine the return value of the program, depending on the return value, to execute different commands (the return value must be in the order of magnitude to small). If the return value equals the specified number, the condition is set up, run the command, or run the next sentence.

Such as:if errorlevel 2 goto x2

The return values from large to small are not required, but are only used when the command is Goto, and when set is used as the execution command, it is usually ordered from small to large, such as the need to place the return code in the environment variable, using the following sequence form:

if errorlevel 1 set el=1if ERRORLEVEL 2 set el=2if ERRORLEVEL 3 set el=3if ERRORLEVEL 4 set el=4if ERRORLEVEL 5 set el=5. .

Of course, you can also use the following loops to replace the principle is consistent:for %%e in (1 2 3 4 5 6 7 8...) do if errorlevel %%e set el=%%e

This occurs because the IF ERRORLEVEL comparison return code is not equal to the judging condition, but is greater than or equal to (>=). Since the goto feature, from small to large sort will cause the small return code at the jump; Because of the "duplicate" assignment of the set command, the large-to-small sort results in a smaller return code that "overwrites" the larger return code.

In addition, although it if errorlevel=<数字> command is also a valid command line, it is only command.com to interpret the command line as a command row and ignore it.

Goto statement

Goto batch file Run here will jump to the label specified by Goto (label is label, labeled with: followed by standard string to define), goto statement is usually used with if, according to different conditions to execute different command groups.

Such as:

Goto End:endecho This is the end

The label is used :字符串 to define the line where the label is not executed.

Labels are often translated as "tags", but this is not broadly agreed.

gotoAnd in conjunction with the implementation of the : middle of the jump, and then the if can implement the conditions of the branch, multiple if can implement the command grouping, similar to the C switch case structure or Basic in the Select Case structure, large-scale and structured command grouping is Functions in high-level languages can be implemented.

Choice statements

Choice Use this command to allow the user to enter a character (for selection), to return different ERRORLEVEL based on the user's choice, and then to run different commands according to the user's choice, if errorlevel mates.

Note: The choice command is a DOS or Windows system-provided external command, different versions of the choice command syntax will be slightly different, please use the choice/? View usage.

Choice command syntax (this syntax is the syntax for the Choice command in Windows 2003, and the command syntax for other versions of choice is similar):

CHOICE [/C choices] [/n] [/cs] [/T timeout/d CHOICE] [/M text] Description: The tool allows the user to select an item from the selection list and return the index of the selected item. Parameter list:/C choices Specifies the list of options to be created. The default list is "YN". /n Hides the list of options in the prompt. Prompts the previous message to be displayed, and the option is still enabled. /cs allows selection of case-sensitive options. By default, this tool is case-insensitive. /T Timeout The number of seconds to pause before making a default selection. The acceptable values are from 0 to 9999. If you specify 0, there will be no pauses, and the default option will be selected. /d Choice Specify the default options after nnnn seconds. The character must be in a set of choices specified with the/C option; At the same time, nnnn must be specified with/T. /M text Specifies the message to display before prompting. If not specified, the tool displays only the hint. /? Displays the help message. Note: The ERRORLEVEL environment variable is set to the key index selected from the selection set. The first selection listed returns 1, the second option returns 2, and so on. If the user presses a key that is not a valid selection, the tool emits a warning beep. If the tool detects an error state, it returns a ERRORLEVEL value of 255. If the user presses the Ctrl+break or CTRL + C key, the tool returns a value of 0 ERRORLEVEL. When you use the ERRORLEVEL parameter in a batch program, the parameters are sorted in descending order. Example: CHOICE/? CHOICE/C ync/m "Confirm please press Y, no press N, or cancel please press C. "Choice/t 10/c ync/cs/d ychoice/c ab/m" option 1 Please select a, option 2 please select B. "Choice/c ab/n/M" option 1 Please select a, option 2 please select B. "

Example: The contents of Test.bat are as follows (* * Note that when you use if errorlevel to determine the return value, you want to sort by the return value from highest to lowest * *):

@echo offchoice/c dme/m "Defrag,mem,end":: if errorlevel 3 goto end::if ERRORLEVEL 2 goto mem::if errorlevel 1 goto Defra G:defragc:\dos\defraggoto End:memmemgoto End:endecho Good bye

After this batch is run, the defrag,mem,end[D,M,E]? user can select D m e, then the IF statement according to the user's choice to make a judgment, D for the execution of the code labeled Defrag, M for the execution of the program segment labeled MEM, E for the execution of the code is the end of the program segment, each end of the program is Goto End jumps The program to the end label, and the program displays good bye, and the batch runs to the end.

For loop

The For loop command, which executes the same command multiple times, as long as the condition conforms.

Syntax: Executes a specific command for each file in a set of files. For%%variable in (set) does command [Command-parameters] (SET) specifies one or a set of files. Wildcard characters can be used. command specifies the commands to execute on each file. Command-parameters specify parameters or command-line switches for specific commands. For example, there is a single line in a batch file: for%%c in (*.bat *.txt) does type%%c the command line displays the contents of all files in the current directory with the name extension of bat and txt.

It is important to note that when a () string is not a single or multiple file names, it is simply substituted as a string, and this feature, plus (), can embed multiple strings, and it is obvious that for can be considered a traversal loop.

Batch processing Example If-exist
    • First, use Notepad to create a test1.bat batch file in the C: \ file with the following contents.
      @echo offif EXIST \autoexec. BAT TYPE \autoexec. Batif not EXIST \autoexec. BAT ECHO \autoexec. BAT does not exist

Then run it:C:\>TEST1.BAT

If C: \ has a Autoexec.bat file, its contents are displayed and if it does not exist, the batch will prompt you that the file does not exist.

    • Next, create a Test2.bat file that reads as follows:
      @ECHO offif EXIST \%1 TYPE \%1if not EXIST \%1 ECHO \%1 does not EXIST

Execute: C:\>TEST2 AUTOEXEC.BAT , the command runs the same result as above.

Description

(1) If EXIST is used to test whether a file exists, in the form of IF EXIST [路径+文件名] 命令 ;

(2) The%1 in the Test2.bat file is a parameter, and DOS allows 9 batch parameter information to be passed to the batch file,%1~%9 (% 0 represents the Test2 command itself), which is somewhat like the relationship between the actual parameter and the formal parameter in the programming, and%1 is the formal parameter, AUTOEXEC. BAT is an argument.

DOS does not have the "only allow 9 batch parameter information" limit, the number of parameters will only be limited by the command length and the processing power of the command called. However, we can only reference 10 parameters at the same time in a batch program, because DOS only gives the%0~%9 10 parameter references.

    • Further, create a file named Test3.bat, which reads as follows:
      @echo offif "%1" = = "A" echo xiaoif "%2" = = "B" echo tianif "%3" = = "C" Echo XIN

If you run: C:\>TEST3 A B C , the screen will display:

Xiaotianxin

If you run: C:\>TEST3 A B , the screen will display:

Xiaotian

During the execution of this command, DOS assigns an empty string to the parameter,% 3.

If-errorlevel

Set up the Test4.bat, which reads as follows:

@ECHO offxcopy C:\AUTOEXEC. BAT d:if ERRORLEVEL 1 echo file copy failed IF ERRORLEVEL 0 echo successfully copied file

Then execute the file:C:\>TEST4

If the file copy succeeds, the screen will display a "Copy file successfully" or the "copy of file failed" will be displayed.

IF ERRORLEVEL is used to test the return value of its previous DOS command, note that it is only the return value of the previous command, and the return value must be judged in order from large to small.

Therefore, the following batch file is incorrect:

@ECHO offxcopy C:\AUTOEXEC. BAT d:if ERRORLEVEL 0 echo Successful copy file if ERRORLEVEL 1 echo not found copy file if ERRORLEVEL 2 echo user ctrl-c abort copy operation if ERRORLEVEL 3 echo preset error Mistakenly block file copy operations if ERRORLEVEL 4 ECHO copy process write disk error if ERRORLEVEL judgment is greater than equals judgment
  • Common Command return values
    Here are the return values of several commonly used commands and what they mean: Backup0 backup succeeded 1 not found backup file 2 file sharing conflict blocked backup complete 3 user aborted backup 4 due to fatal error making backup operation abort diskcomp0 disk Compare 1 disk compare same 2 The user aborts the comparison operation by Ctrl-c 3 due to a fatal error to make the comparison operation abort 4 preset error abort compare diskcopy0 disk copy operation succeeded 1 non-fatal disk read/write error 2 user over ctrl-c end copy Operation 3 due to fatal processing error make disk copy abort 4 Preset error prevents copy operation FORMAT0 format successfully 3 user ctrl-c abort format processing 4 due to fatal processing error to make formatting abort 5 at the prompt "Proceed with format (y/n)?" Under User type N end xcopy0 successful copy file 1 not found copy file 2 user ctrl-c abort copy Operation 4 Preset error block file copy operation 5 copy process write disk error Chkdsk0 not found error 255 found one or more errors Choice0 user pressed ctrl+c/ BREAK1 the user presses the first key 255 detects the error condition in the command line other users press valid characters in the list position defrag0 fragmentation compression succeeds 1 there is an internal error 2 there is no empty cluster on the disk. To run defrag, you must have at least one empty cluster 3 users quit with CTRL + C DEFRAG4 General error 5 defrag encountered error when reading a cluster 6 defrag encountering error 7 allocating space when writing a cluster 8 memory errors 9 There is not enough space to compress disk fragmentation DELTREE0 Successfully deleted a directory diskcomp0 two disks the same 1 found different 2 press CTRL + C terminated the comparison 3 occurred critical Error 4 occurred initialization error FIND0 lookup succeeded and found at least one matching string 1 lookup succeeded but did not find a matching string 2 error occurred in the lookup keyb0 Keyboard definition file loading succeeded 1 using illegal keyboard code, character set or Syntax 2 keyboard definition file bad or not found 4 keyboard, monitor communication error 5 required character set not ready MOVE0 successfully moved the specified file 1 An error msav/n86 checked to the virus replace0 REP Lace successfully replaced or joined the file 1 MS-DOS version and replace incompatible 2 replace cannot find source file 3 Replace cannot find source path or destination path 5 cannot access file to replace 8 memory not enough to execute REPLACE11 Command-line syntax error RESTORE0 restore successfully recovered file 1 RESTore cannot find the file to recover 3 user presses CTRL + C to terminate the recovery Process 4 restore is terminated with an error scandisk0 ScanDisk does not detect any error on the drive it checks for 1 because the command line syntax is not correct, you cannot run ScanDisk2 ScanDisk unexpected termination due to memory exhaustion or internal error 3 users let ScanDisk exit 4 for a disk scan, the user decides to exit early 254 ScanDisk find the disk failure and have all corrected 255 ScanDisk find disk failure, But failed to fully correct SETVER0 setver successfully completed task 1 user specified an invalid command switch 2 user specified an illegal file name 3 not enough system memory to run command 4 user specified an illegal version number format 5 Setver The specified item was not found in the version table 6 SETVER SETVER.EXE File 7 user specified an illegal drive 8 user specified too many command line arguments 9 SETVER detected missing command line parameter 10 when reading SETVER.EXE file, SETVER detected an error one by one SETVER.  EXE file corruption 12 The specified SETVER.EXE file does not support the version Table 13 version table does not have enough space to hold the new entry 14 when writing the SETVER.EXE file Setver detected an error occurred
IF STRING1 = = STRING2

Establish Test5.bat, the file contents are as follows:

@echo offif "%1" = = "A" FORMAT A:

Execute: C:\>TEST5 A , the screen will appear on whether the A: Disk formatted content.

Note: In order to prevent arguments from being empty, it is common to enclose the string in double quotation marks (or other symbols, note that you cannot use a retention symbol).

Such as:if [%1]==[A] 或者 if %1*==A*

Goto

Establish Test6.bat, the file contents are as follows:

@ECHO offif EXIST C:\AUTOEXEC. BAT GOTO _copygoto _done:_copycopy C:\AUTOEXEC. BAT D::_done
    • Attention:
      1. Before the label is the colon ":" of the ASCII character, there can be no spaces between the colon and the label.
      2. The naming convention for a label is the same as the naming convention for a file name (the signature cannot start with most non-alphanumeric characters, and a lot is available in the file name).
      3. DOS supports labels with a maximum of eight characters, and when two labels cannot be distinguished, jumps to the top-most label of the position.
For

Establish C:\TEST7. BAT, the file contents are as follows:

@ECHO offfor%%C in (*. BAT *. TXT *. SYS) do TYPE%%C

Run:C:\>TEST7

After execution, the screen will display all the contents of the file (excluding hidden files) in the C: Packing directory with the name extension of bat, TXT, sys.

Establish Test.cmd

@ECHO offfor%%C in (%*) does @ECHO%%cecho---------------for%%C in (%*) do (for/l%%i In (1,1,2) does echo%%c%%i) echo---------------for%%C in (%*) do (   for/l%%i In (3,1,4) do echo%%c-%%i      )

Run: test.cmd a b , enter the following:

AB---------------a1a2b1b2---------------a-3a-4b-3b-4
Command List
  • Version: Microsoft Windows XP [version 5.1.2600]
  • For more information about a command, type: HELP 命令名 view.
  • Command List
    ASSOC Displays or modifies file name extension associations. At Schedules commands and programs to run on the computer. ATTRIB Display or change file properties. Break sets or clears the extended CTRL + C check. CACLS displays or modifies the file's access control List (ACLs). Call calls this one from another batch program. The CD displays the name of the current directory or changes it. CHCP Displays or sets the number of active code pages. CHDIR displays the name of the current directory or changes it. CHKDSK checks the disk and displays the status report. CHKNTFS Displays or modifies the startup time disk check. CLS clears the screen. CMD opens another Windows command interpreter window. Color sets the default console foreground and background color. COMP compares the contents of two or two sets of files. Compact displays or changes the compression of files on NTFS partitions. Convert converts a FAT volume to NTFS. You cannot convert the current drive. Copy copies at least one of the files to another location. Date Displays or sets dates. DEL deletes at least one file. DIR displays the files and subdirectories in a directory. DISKCOMP compares the contents of two floppy disks. DISKCOPY Copy the contents of one floppy disk to another. DOSKEY Edit the command line, invoke the Windows command, and create a macro. echo Displays the message, or turns the command back on or off. Endlocal to end localization of environment changes in batch files. ERASE Delete at least one file. Exit CMD. EXE Program (command interpreter). FC compares two or two sets of files and displays different places. Find searches the file for a text string. FINDSTR searches for strings in the file. For each file in a set of files, run a specified command. Format formats the disk for use with Windows. FTYPE displays or modifies the file types used for file name extension associations. GOTO points The Windows command interpreter to a marked line in the batch program. GRAFTABL enable Windows to display the extended character set in image mode. Help provides information about Windows commands. IF you perform conditional processing in a batch program. Label creates, changes, or deletes a disk's volume label. MD to create a directory. MKDIR Create directory. MODE configures the system device. More displays a result screen at a time. Move moves files from one directory to another. Path displays or sets the search path for the executable file. Pause pauses processing of batch files and displays messages. POPD restores the previous value of the current directory saved by PUSHD. Print prints a text file. PROMPT change the Windows command prompt. PUSHD Save the current directory and make changes to it. RD Delete directory. RECOVER recovers readable information from the problematic disk. REM record batch file or CONFIG. The comment in SYS. REN renames the file. RENAME Rename the file. Replace replaces the file. RMDIR Delete the directory. Set to display, set, or remove Windows environment variables. SETLOCAL the localization of the environment changes in the batch file. SHIFT replaces the position of replaceable parameters in the batch file. Sort to categorize the input. Start starts another window to run the specified program or command. SUBST associates the path with a drive letter. Time displays or sets the system times. The TITLE sets CMD. The window caption of the EXE session. Tree displays the directory structure of a drive or path in graphical mode. TYPE Displays the contents of the text file. VER shows the version of Windows. VERIFY tells Windows whether to verify that the file is written to disk correctly. VOL Displays the disk volume label and serial number. XCOPY Copy files and directories

Windows Batch Learning---

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.