In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/02 Report--
Catalogue
Common commands for batch processing (there are still many commands not enumerated, please check the help information)
1. REM and:
2, ECHO and @
3 、 PAUSE
4 、 ERRORLEVEL
5 、 TITLE
6 、 COLOR
7. Mode configures system devices
8. GOTO and:
9 、 FIND
10 、 START
11, assoc and ftype
12. Pushd and popd
13 、 CALL
14 、 shift
15 、 IF
16. Setlocal and variable delay
17. ATTRIB displays or changes file properties
=
Introduction command
1. REM and:
REM is a comment command, which is generally used to annotate the program. The content after the command is not executed, but can be echoed.
Second,:: can also play the role of rem annotation, and more concise and effective, but there are two points to note:
First, any character line that begins with a colon is treated as a label in the batch and everything that follows is directly ignored.
Valid label: the colon is followed by an alphanumeric string that can be recognized by the goto statement.
Invalid label: the colon is followed by a special symbol that is not alphanumeric, and the label that goto cannot recognize can play the role of annotation, so:: is often used as an annotation symbol, in fact: + can also play the role of annotation.
Second, unlike rem, the character line after:: will not be echoed when executed, regardless of whether you open the command line echo state with echo on or not, because the command interpreter does not think it is a valid command line, from this point of view, rem will be more applicable than:: in some cases; in addition, rem can be used in config.sys files.
Inline comment format:% comment content% (not commonly used, use with caution)
2, ECHO and @
Placing the @ character in front of a command turns off the echo of the command, regardless of whether the echo is open or not.
The functions of the echo command are listed as follows:
(1) turn echo on or off
Format: echo [{on | off}]
If you want to turn off the display of the "ECHO OFF" command line itself, you need to precede the command line with "@".
(2) display the current ECHO setting status
Format: echo
(3) output prompt information
Format: ECHO message content
These are the three common uses of the ECHO command, which you are familiar with and can use, but as a gold digger of the DOS command, you should also know the following techniques:
(4) close the DOS command prompt
By typing ECHO OFF at the DOS prompt, you can turn off the display of the DOS prompt so that only the cursor is left on the screen until you type ECHO ON before the prompt reappears.
(5) output a blank line, which is equivalent to entering an enter
Format: ECHO.
It is worth noting that the "." on the command line should be followed by ECHO without a space, otherwise "." will be output to the screen as a prompt. In addition, "." can be replaced with any symbol such as,:; / [\] +.
The return of the command ECHO. Output can be turned through the DOS pipeline as input to other commands, such as echo. | time is equivalent to giving a carriage return after the execution of the TIME command. So when executing, the system will automatically return to the DOS prompt after the current time is displayed.
(6) reply to questions in the order
Format: ECHO reply | Command file name
The above format can be used to simplify the operation of some commands that require man-machine dialogue (such as: CHKDSK/F;FORMAT Drive:;del *.). It uses the preset response language output of the ECHO command as the input of the man-machine dialogue command through the DOS pipeline command. The following example is equivalent to entering "Y" enter when a man-machine conversation occurs in the invoked command:
C: > ECHO Y | CHKDSK/F
C: > ECHO Y | DEL A: *. *
(7) create new documents or add document contents.
Format: ECHO file content > file name
ECHO file contents > > file name
For example:
C: > ECHO @ ECHO OFF > AUTOEXEC.BAT sets up automatic batch files
C: > ECHO C:\ CPAV\ BOOTSAFE > > AUTOEXEC.BAT appends content to the automatic batch file
C: > TYPE AUTOEXEC.BAT displays the automatic batch file
@ ECHO OFF
C:\ CPAV\ BOOTSAFE
(8) output the printed content or print control code to the printer
Format: ECHO printer control code >; PRN
ECHO print content >; PRN
The following example is to input a print control code to the MMel 1724 printer. < Alt > 156 is to hold down the alt key and type 156 on the keypad, and so on:
C: > ECHO + 156 / 42 / 116 >; PRN (enter the underscore command FS*t)
C: > ECHO [email=+155@] + 155 @ >; PRN [/ email] (enter the initialization command ESC@)
C: > ECHO. >; PRN (newline)
(9) make the horn sound
C: > ECHO ^ G
"^ G" is entered with Ctrl+G or Alt+007 in the dos window. Entering multiple ^ G can produce multiple tones. The way to use it is to add it directly to the batch file or make it into a batch file call.
The "^ G" here belongs to the use of special symbols. Please see the later chapter of this article.
3 、 PAUSE
PAUSE, everyone who plays the game knows the meaning of time-out.
In this case, stop the execution of the system command and display the following.
Example:
PAUSE
The run shows:
Please press any key to continue. . .
To display other prompts, you can use:
Other prompts for Echo & pause > nul
4 、 errorlevel
Program return code
Echo errorlevel%
At the end of each command run, you can view the return code in this command line format
Used to judge whether the command just was executed successfully
The default value is 0. If an error occurs in the execution of a command, errorlevel is set to 1.
5 、 title
Set the title of the cmd window
Title new title # you can see that the title bar of the cmd window has changed
6 、 COLOR
Sets the default console foreground and background colors.
COLOR [attr]
Attr specifies the color attribute of the console output
The color property is specified by two hexadecimal digits-the first is the background and the second is
Foreground. Each number can be one of the following values:
0 = black 8 = gray
1 = blue 9 = light blue
2 = green A = light green
3 = lake blue B = light green
4 = red C = light red
5 = purple D = lavender
6 = × × × E = light × × ×
7 = White F = bright white
If no parameters are given, the command restores the color to when CMD.EXE starts
It's the color. This value comes from the current console window, / T switch, or
DefaultColor registry value.
If you execute the COLOR command with the same foreground and background color, the COLOR command
ERRORLEVEL is set to 1.
For example, "COLOR fc" produces bright red on bright white.
7. Mode configures system devices
Configure system devices.
Serial port: MODE COMm [:] [BAUD=b] [PARITY=p] [DATA=d] [STOP=s]
[to=on | off] [xon=on | off] [odsr=on | off]
[octs=on | off] [dtr=on | off | hs]
[rts=on | off | hs | tg] [idsr=on | off]
Device status: MODE [device] [/ STATUS]
Print redirection: MODE LPTn [:] = COMm [:]
Selected code page: MODE CON [:] CP SELECT=yyy
Code page status: MODE CON [:] CP [/ STATUS]
Display mode: MODE CON [:] [COLS=c] [LINES=n]
Keystroke rate: MODE CON [:] [RATE=r DELAY=d]
Example:
Mode con cols=113 lines=15 & color 9f
This command sets the DOS window size: 15 rows, 113 columns
8. GOTO and:
GOTO's friends who know how to program will know that this means jump.
It is allowed to build a label with ": XXX" in the batch, then use GOTO XXX to jump to the label: XXX, and then execute the labeled command.
Example:
If {% 1} = = {} goto noparms
If "% 2" = "" goto noparms
The name of the tag can be chosen at will, but it is better to be a meaningful string, preceded by a colon to indicate that the string is a tag, and the goto command is based on this colon (:) to find the next step to jump there. You'd better have some instructions so that you and others will seem to understand your intentions.
Example:
@ echo off
: start
Set / a var+=1
Echo var%
If var% leq 3 GOTO start
Pause
The run shows:
one
two
three
four
9 、 find
Search for strings in the file.
FIND [/ V] [/ C] [/ N] [/ I] [/ off [line]] "string" [[drive:] [path] filename [...]]
/ V displays all lines that do not contain the specified string.
/ C displays only the number of lines that contain a string.
/ N displays the line number.
/ I ignores case when searching for strings.
/ OFF [LINE] do not skip files with offline property sets.
"string" specifies the text string to search for
[drive:] [path] filename
Specify the files to search for.
If no path is specified, FIND searches for text typed or generated by another command.
Find is often used in conjunction with the type command
Type [drive:] [path] filename | find "string" [> tmpfile] # pick lines containing string
Type [drive:] [path] filename | find / v "string" # remove lines containing string in the file
Type [drive:] [path] filename | find / c # shows the number of file lines
The above usage removes the prompt (file name prompt) that comes with the find command.
Example:
@ echo off
Echo 111 > test.txt
Echo 22 > > test.txt
Find "1111" test.txt
Del test.txt
Pause
The run is shown as follows:
-TEST.TXT
one hundred and eleven
Please press any key to continue. . .
Example:
@ echo off
Echo 111 > test.txt
Echo 22 > > test.txt
Type test.txt | find "111"
Del test.txt
Pause
The run is shown as follows:
one hundred and eleven
Please press any key to continue. . .
10. Start command
A command that invokes an external program in a batch (the external program runs in a new window, and the batch program continues to execute, regardless of the running status of the external program). If you run the external program directly, you must wait for the external program to complete before continuing to execute the remaining instructions
Example: start explorer d:\
Call the graphical interface to open the D disk
11, assoc and ftype
File association
Assoc sets the 'file extension' association, associated to the 'file type'
Ftype sets the 'file type' association, which is associated with the 'executor and parameters'
When you double-click a .txt file, windows does not open it with notepad.exe based on the .txt direct judgment.
Instead, it is judged that .txt belongs to txtfile 'file type'.
Then call the command line associated with txtfile txtfile=%SystemRoot%\ system32\ NOTEPAD.EXE% 1
You can modify these two associations in "folder options" → "File types".
Assoc # shows all 'file extension' associations
Assoc .txt # shows the file type represented by .txt, and the result shows .txt = txtfile
Assoc .doc # shows the file type represented by .doc, and the result shows .doc = Word.Document.8
Assoc .exe # shows the file type represented by .exe, and the result shows .exe = exefile
Ftype # shows all 'file type' associations
Ftype exefile # displays the command line associated with the exefile type, which shows exefile= "% 1"% *
Assoc .txt = Word.Document.8
If you set .txt to a document of type word, you can see that the icons of the .txt file have changed.
Assoc .txt = txtfile
Restore the correct association of .txt
Ftype exefile='1'% *
Restore the correct association of exefile
If the association has been broken, you can run command.com and enter this command
12. Pushd and popd
Toggle current directory
@ echo off
C: & cd\ & md mp3 # create a mp3 folder in C:\
Md d:\ mp4 # create a mp4 folder in D:\
Cd / d d:\ mp4 # change the current directory to d:\ mp4
Pushd c:\ mp3 # saves the current directory and changes the current directory to c:\ mp3
Popd # restore the current directory to the d:\ mp4 you just saved
It is generally not very useful, and it will be helpful when the current directory name is uncertain. (useful in dos programming)
13 、 CALL
The CALL command can invoke another batch during batch execution, and then continue to execute the original batch after the other batch has been executed.
CALL command
Invoking a batch command has the same effect as executing the command directly, which is useful in special cases, such as multi-level nesting of variables, as shown later in the tutorial. In batch programming, you can generate a command string according to certain conditions, which can be executed with call, as shown in the example.
CALL [drive:] [path] filename [batch-parameters]
Other batch programs called. The filename parameter must have a .bat or .cmd extension.
CALL: label arguments
Call the command section in this file, which is equivalent to a subroutine. The called command segment begins with the label: label
Ends with the command goto: eof.
In addition, the parameters of the script (% 0,% 1, etc.) have been changed as follows:
The% * in the batch script indicates all parameters (such as% 1% 2% 3% 4% 5.)
The substitution of the batch parameter (% n) has been enhanced. You can use the following syntax: (run the following example directly if you don't understand)
% ~ 1-delete quotation marks ("), expand% 1
% ~ F1-extends% 1 to a fully qualified pathname
% ~ D1-expand% 1 to only one drive letter
% ~ p1-extend% 1 to only one path
% ~ N1-expand% 1 to only one file name
% ~ x1-extend% 1 to only one file extension
The path of% S1-extension contains a short name
% ~ A1-extends% 1 to file attributes
% ~ T1-extend% 1 to the date / time of the file
% ~ Z1-expand% 1 to the size of the file
% ~ $PATH: 1-find the directory listed in the PATH environment variable and set% 1
Expand to the first fully qualified name found. If the environment
If the variable name is not defined, or the file is not found, this key combination will
Expand to an empty string
You can combine modifiers to achieve multiple results:
% ~ dp1-extends% 1 only to the drive letter and path
% ~ nx1-extends% 1 only to the file name and extension
% ~ dp$PATH:1-look for% 1 in the directory listed in the PATH environment variable
And expand to the drive letter and path of the first file found.
% ~ ftza1-extends% 1 to output lines like DIR.
In the above example,% 1 and PATH can be replaced by other valid values.
% ~ the syntax is terminated by a valid parameter number. % ~ modifier cannot be used with% *
Note: when expanding the parameter, regardless of whether the file represented by the parameter exists or not, it is expanded with the current directory.
To understand the above knowledge, the following example is crucial.
Example:
@ echo off
Echo generates a temporary file > tmp.txt
The Rem downlink saves the current directory first, and then sets c:\ windows as the current directory
Pushd c:\ windows
Call: sub tmp.txt
The Rem downlink restores the current directory of the previous one
Popd
Call: sub tmp.txt
Pause
Del tmp.txt
Exit
: sub
Echo delete quotation marks:% ~ 1
Echo extended to path:% ~ F1
Echo is extended to a drive letter:% ~ D1
Echo extends to a path:% ~ p1
Echo is expanded to a file name:% ~ N1
Echo extends to a file extension:% ~ x1
The path to the Echo extension contains the short name:% ~ S1
Echo is extended to file attribute:% ~ A1
Date / time when Echo was extended to the file:% ~ T1
Echo extends to file size:% ~ Z1
Echo extends to drive letter and path:% ~ dp1
Echo extends to file name and extension:% ~ nx1
Echo extends to output lines like DIR:% ~ ftza1
Echo.
Goto: eof
Example:
Set aa=123456
Set cmdstr=echo aa%
Call cmdstr%
Pause
In this example, running% cmdstr%, instead of call will show the result% aa%, instead of 123456
14 、 shift
Change the location of replaceable parameters in the batch file.
SHIFT [/ n]
If the command extension is enabled, the SHIFT command supports the / n command line switch, which tells the
The command shifts from the nth argument; n is between zero and eight. For example:
SHIFT / 2
Will shift 3 to 2, 4 to 3, and so on; and will not affect 0 and 1.
15 、 IF
The syntax format of IF conditional judgment statement is as follows:
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
The following is described one by one. For a more detailed analysis, please see the following chapters.
(1) IF [NOT] ERRORLEVEL number command
The sentence IF ERRORLEVEL must be placed after a command, and it is up to IF ERRORLEVEL to determine the return value of the command after the command is executed.
The numerical value range of Number is 0255. it is judged that the order of values should be from large to small. The condition holds when the returned value is greater than or equal to the specified value.
Example:
@ echo off
Dir c:
If the rem exit code is > = 1, jump to heading 1, and jump to title 0 if > = 0.
IF ERRORLEVEL 1 goto 1
IF ERRORLEVEL 0 goto 0
The two lines above the Rem cannot be swapped, otherwise failure will show success.
: 0
The echo command was executed successfully!
After the execution of the Rem program, jump to the title exit and exit.
Goto exit
: 1
Failed to execute the echo command!
After the execution of the Rem program, jump to the title exit and exit.
Goto exit
: exit
Pause
The operation shows that the command was executed successfully!
(2) IF [NOT] string1==string2 command
String1 and string2 are both character data. The case of characters in English will be regarded as different. In this condition, the equal sign must be two (absolutely equal).
When the conditions are equal, the subsequent command is executed.
To detect the value of the current variable to make a decision, to prevent spaces in the string, you can use the following format
If [NOT] {string1} = = {string2} command
If [NOT] [string1] = = [string2] command
If [NOT] "string1" = = "string2" command
This way of writing actually treats parentheses or quotation marks as part of a string, as long as the left and right sides of the equal sign are consistent, such as the following:
If {string1} = = [string2] command
(3) IF [NOT] EXIST filename command
EXIST filename means the existence of a file or directory
Echo off
IF EXIST autoexec.bat echo file exists!
IF not EXIST autoexec.bat echo file does not exist!
You can execute this batch on disk C and disk D respectively to see the effect.
16. Setlocal and variable delay
The content of this article refers to the batch processing tutorial produced by Hero:
If you want to advance, variable delay is a must! So I hope you can take a closer look at this part.
In order to better illustrate the problem, let's introduce an example first.
Example 1:
@ echo off
Set axi4
Set astat5 & echo% a%
Pause
Results: 4
Explanation: why 4 instead of 5? Have you changed the value of variable a to 5 before echo?
Let's first take a look at the mechanism for batch running commands:
When a batch reads a command, it is read by line (for example, the for command, etc., and all statements closed with a pair of parentheses are treated as one line), and the necessary preprocessing work is completed before processing, including the assignment of variables in the line command. Let's now analyze example 1. The batch process reads and preprocesses the whole sentence before running to the sentence "set a% & echo% a%"-- if you assign a value to the variable a, then% a% is of course 4! (for no reason, that's what batch processing does. )
In order to perceive the dynamic changes of environmental variables, the variable delay is designed for batch processing. To put it simply, after reading a complete statement, the variable of the row is not assigned immediately, but before a single statement is executed, that is, the assignment of the variable is "delayed".
So how do you turn on variable delay? What do you need to pay attention to about variable delay? Give an example to illustrate:
Example 2:
@ echo off
Setlocal enabledelayedexpansion
Set axi4
Set axiom 5 & echo! a!
Pause
Results: 5
Explanation: variable delay is started and the correct answer is obtained. The delayed startup statement for the variable is "setlocal enabledelayedexpansion", and the variable uses a pair of exclamation marks "!!" Wrap it up (pay attention to the English exclamation mark), otherwise there will be no effect of variable delay.
To analyze example 2, first "setlocal enabledelayedexpansion" turns on the variable delay, and then "set axiom 4" first assigns the variable a to
4, "set averse 5 & echo! a!" This sentence assigns the variable a to 5 and outputs (because of the delay in starting the variable, the batch can sense the dynamic change, that is, it does not assign a value to the variable first, but to the variable during operation, so the value of an is 5).
Give me another example to consolidate it.
Example 3:
@ echo off
Setlocal enabledelayedexpansion
For / l% I in (1mem1mem5) do (
Set aversion%% I
Echo! a!
)
Pause
Results:
one
two
three
four
five
Explanation: this example turns on variable delay and uses "!!" Expand the variables so that we get the expected results. What happens if you don't use variables to delay?
What's the result? The result is this:
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
That is, you are not aware of the dynamic changes in the for statement.
Tip: in the case of no delay in opening variables, variable changes in a command line must not be reflected until the next command. This point can also be taken advantage of. Look at the example.
Example: exchange the values of two variables without intermediate variables
@ echo off
Purpose: exchange the values of two variables, but do not use temporary variables
Code by JM 2007-1-24 [email=CMD@XP] CMD@ XP [/ email]
:: source: http://www.cn-dos.net/forum/viewthread.php?tid=27078
Set var1=abc
Set var2=123
Before echo switching: var1=%var1% var2=%var2%
Set var1=%var2%& set var2=%var1%
After echo exchange: var1=%var1% var2=%var2%
Pause
17. ATTRIB displays or changes file properties
ATTRIB [+ R |-R] [+ A |-A] [+ S |-S] [+ H |-H] [[drive:] [path] filename] [/ S [/ D]]
+ set properties.
-clear the attribute.
R read-only file properties.
An Archive file properties.
S system file properties.
H hides file properties.
[drive:] [path] [filename]
Specifies the file properties to be processed.
/ S processes matching files in the current folder and its subfolders.
/ D also handles folders.
Example:
Md autorun
Attrib + a + s + h autorun
The above command creates the folder autorun, and then sets it as archive, system, hidden properties
=
Section 2 Special symbols commonly used
1. @ command line echo mask
2.% batch variable leader
3. > redirector
4, > > redirector
5. &, redirector
Output redirect command
The standard input and output of DOS are usually carried out on standard equipment keyboards and monitors, and using redirection, you can easily change the input and output to disk files or other devices. Where:
1. The greater than sign ">" sends commands to a file or device, such as printer > prn. When using the greater than sign ">", some command outputs, such as error messages, cannot be redirected.
two。 The double greater than sign "> >" adds the command output to the end of the file without deleting the information already in the file.
3. Less than sign "> temp.txt
Echo "4444" 44 > > temp.txt
Echo ^ "55" 55 "55 > temp.txt
Set up temporary files on rem. Note that unpaired quotation marks should be accompanied by escape characters ^. Do not leave spaces before redirecting symbols.
FOR / F "delims="% I IN (temp.txt) DO echo% ~ I
Pause
Del temp.txt
After execution, we see the echo of CMD as follows:
The quotation marks before the 1111 # string have been deleted
The quotation marks at the beginning and end of the 2222 # string have been deleted.
3333 "# string is preceded by quotation marks, followed by quotation marks reserved
The quotation marks before the 4444 "44 # string are deleted, while the quotation marks in the middle are retained.
The quotation marks before the 55 "55" 55 # string are deleted, while the quotation marks in the middle are retained.
Please press any key to continue. . .
Compared with the previous temp.txt, we will find that the quotation marks on lines 1, 2, and 5 have disappeared, which is the purpose of deleting quotation marks ~ I!
The rules for deleting quotation marks are as follows (added by brother BAT!)
1. If there are quotation marks at the beginning and end of the string, delete the quotation marks at the beginning and the end of the string
2. If there are no quotation marks at the end of the string, delete the quotation marks at the beginning of the string
3. If there are quotation marks in the middle of the string, or if there are only quotation marks at the end, they are not deleted.
Tornado added: every head does not delete, there is a head even tail deletion.
2.% ~ fI-extends% I to a fully qualified pathname
Look at the example:
Save the code anywhere, and I'll put it on the desktop here.
FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ fi
Pause
The content displayed after execution is as follows
C:\ Documents and Settings\ Administrator\ Desktop\ test.bat
C:\ Documents and Settings\ Administrator\ Desktop\ test.vbs
When I change% ~ fi in the code directly to% I
FOR / F "delims=="% I IN ('dir / b') DO @ echo% I
Pause
After execution, the following is displayed:
Test.bat
Test.vbs
By comparison, we can easily see that there is no path, which is the function of "extending% I to a fully qualified pathname".
That is, if the content of the% I variable is a file name, he will print out the absolute path where the file is located, instead of just printing a file name, you will know it in the hands-on experiment!
3.% ~ dI-extend% I to only one drive letter
Look at the example:
The code is as follows, I will put it on the desktop for execution!
FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ di
Pause
After execution, my CMD shows the following
C:
C:
There are only two files on my desktop test.bat,test.vbs,%%~di function is that if the content of the variable% I is a file or directory name, he will put his file
Or the disk symbol where the directory is located is printed out!
4.% ~ pI-extend% I to only one path
This usage is the same as above, it only prints the path, not the file name.
FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ pi
Pause
I will not play the results, we copy the code to see the results, the following are all such a usage, the code is given, you see the results!
5.% ~ nI-extends% I to only one file name
Print only the file name
FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ ni
Pause
6.% ~ xI-extend% I to only one file extension
Print only the file extension
FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ xi
Pause
7.% ~ sI-the extended path contains only short names
Print an absolutely short file name
FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ si
Pause
8.% ~ aI-extends% I to the file attributes of the file
Properties of the print file
FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ ai
Pause
9.% ~ tI-extends% I to the date / time of the file
Date on which the print file was created
FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ ti
Pause
10.% ~ zI-extends% I to the size of the file
The size of the print file
FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ zi
Pause
The "delims==" in the above example can be changed to "delims=", that is, no delimiter
11.% ~ $PATH:I-find the directory listed in the path environment variable
And extend% I to the first fully qualified name found. If the environment variable name is not defined, or if the file is not found, this key combination is extended to an empty string
This is the last one, which is different from the ones above. I'll talk about it alone!
Then save the code as a batch and put it on the desktop.
@ echo off
FOR / F "delims="% I IN ("notepad.exe") DO echo% ~ $PATH:i
Pause
Tornado add: the above code shows the result as C:\ WINDOWS\ system32\ notepad.exe
He means to search the notepad.exe file in the path specified in the PATH variable, and if there is a notepad.exe, it will print out his absolute path, and if not, print an error!
All right, that's all for FOR's variables!
=
Chapter IV variables in batch processing
I divide the variables in the batch into two categories, namely "system variables" and "custom variables".
Now let's explain these two variables in detail!
I. system variables
Their values are automatically assigned by the system according to pre-defined conditions, that is, these variables have been defined by the system.
We don't need to assign a value to him, we just need to call it! I'll list them all!
% ALLUSERSPROFILE% returns the location of the all users profile locally.
% APPDATA% returns locally the location where the application stores data by default.
% CD% returns the current directory string locally.
% CMDCMDLINE% returns the exact command line used to start the current Cmd.exe locally.
The% CMDEXTVERSION% system returns the version number of the current Command processor extension.
The COMPUTERNAME% system returns the name of the computer.
The% COMSPEC% system returns the exact path to the command line interpreter executable.
The DATE% system returns the current date. Use the same format as the date / t command. Generated by Cmd.exe. Related
For more information about the date command, see Date.
The ERRORLEVEL% system returned the error code of the previous command. Errors are usually represented by a non-zero value.
The% HOMEDRIVE% system returns the local workstation drive letter connected to the user's home directory. Set based on the home directory value. Use
The household directory is specified in Local users and groups.
The% HOMEPATH% system returns the full path to the user's home directory. Set based on the home directory value. The user home directory is specified in Local users and groups.
The HOMESHARE% system returns the network path of the user's shared home directory. Set based on the home directory value. The user's home directory is
Specified in Local users and groups.
% LOGONSERVER% returns locally the name of the domain controller that validates the current login session.
The NUMBER_OF_PROCESSORS% system specifies the number of processors installed on the computer.
The OS% system returns the operating system name. Windows 2000 shows that its operating system is Windows_NT.
The PATH% system specifies the search path for executable files.
The% PATHEXT% system returns a list of file extensions that the operating system considers executable.
% PROCESSOR_ARCHITECTURE% system returns the chip architecture of the processor. Value: x86 or IA64 based on
Itanium
% PROCESSOR_IDENTFIER% system returned processor description.
The PROCESSOR_LEVEL% system returns the model of the processor installed on the computer.
The PROCESSOR_REVISION% system returns the version number of the processor.
% PROMPT% returns the command prompt settings for the current interpreter locally. Generated by Cmd.exe.
The% RANDOM% system returns any decimal number between 0 and 32767. Generated by Cmd.exe.
% SYSTEMDRIVE% system returned the root directory containing Windows server operating system (that is, system root)
The drive.
The SYSTEMROOT% system returns the location of the Windows server operating system root directory.
The% TEMP% and% TMP% systems and users return the default temporary directory used by the applications available to the currently logged in user.
Some applications require TEMP, while others require TMP.
The TIME% system returns the current time. Use the same format as the time / t command. Generated by Cmd.exe. Related
For more information about the time command, see Time.
% USERDOMAIN% returns locally the name of the domain that contains the user account.
% USERNAME% returns the name of the currently logged in user locally.
% USERPROFILE% returns the location of the current user's profile locally.
The WINDIR% system returns the location of the operating system directory.
With so many system variables, how do we know what their value is?
Enter echo WINDIR% in CMD
So you can display the value of a variable!
For example, we can do this if we want to copy files to the startup directory of the current account.
Copy d:\ 1.bat "% USERPROFILE%\" start menu\ Program\ start\ "
% USERNAME% returns the name of the currently logged in user locally. Note that directories with spaces are enclosed in quotation marks
There are also some system variables that represent the same meaning, or an operation!
They are 0% 1% 2% 3% 4% 5. Until% 9, there is still one% *.
% 0 is a bit special and has several layers of meaning. Let's first talk about the meaning of% 1% 9.
1 returns the first parameter of the batch
2 returns the second parameter of the batch
% 3mer% 9 infer according to this
Return batch parameters? How to return in the end?
Let's look at this example, save the following code as test.BAT and put it on disk C.
@ echo off
Echo 1 2 3 4
Echo 1
Echo 2
Echo 3
Echo 4
Enter CMD and enter cd c:\
Then type test.bat. I'm the first parameter. I'm the second parameter. I'm the third parameter. I'm the fourth parameter.
Notice the space in the middle, and we will see the result like this:
I'm the first parameter. I'm the second parameter. I'm the third parameter. I'm the fourth parameter.
I'm the first parameter.
I'm the second parameter.
I'm the third parameter.
I'm the fourth parameter.
Compared with the code, 1 is "I am the first parameter" and 2 is "I am the second parameter"
How do you understand?
These% 1 and% 9 allow batch processing to run with parameters, greatly improving batch processing capabilities!
There is another% * what is he? It's not very useful, it just returns parameters, but it returns all the parameters at once, and you don't have to enter% 1% 2 to determine one by one.
Examples
@ echo off
Echo% *
Also save as test.bat and put it on disk C.
Enter CMD and enter cd c:\
Then type test.bat. I'm the first parameter. I'm the second parameter. I'm the third parameter. I'm the fourth parameter.
You can see that he shows all the parameters at once.
Okay, now let's talk about the special% 0.
% 0 this is not the value of the return parameter, it has two meanings!
First meaning: return to the absolute path where the batch is located
Example:
@ echo off
Echo 0
Pause
Save it as test.BAT and run it on the desktop, and the result is as follows
"C:\ Documents and Settings\ Administrator\ Desktop\ test.bat"
He prints out the path where the current batch is executed, which means to return the absolute path where the batch is located
The second meaning: infinite loop execution of BAT
Example:
@ echo off
Net user
% 0
Save as BAT and it will loop through the net user command indefinitely until you stop it manually.
Tornado added: in fact,% 0 is the parameter before the first parameter% 1, which is, of course, the batch file name (including path).
These are some of the system variables in the batch, and there are other variables that also represent some functions.
Those in the FOR command are those that have already been said by the FOR variable, so let's not talk about it.
II. Custom variables
Therefore, the name implies that a custom variable is a variable that we assign a value to it.
To use custom variables, you have to use the set command. Look at the example.
@ echo off
Set var=, I'm worth it.
Echo var%
Pause
Save as BAT execution, we will see a "I am the value" returned in CMD.
Var is the variable name, and the value to be given to the variable is changed to the right of the = sign.
This is the easiest way to set variables.
If we want the user to enter the value of the variable manually instead of specifying it in the code, we can use the / p parameter of the set command
Example:
@ echo off
Set / p var= Please enter the value of the variable
Echo var%
Pause
To the right of the var variable name = sign is the prompt, not the value of the variable.
The value of the variable is entered by ourselves with the keyboard after we run it!
I. Interactive interface design
There's nothing to say. Take a look at the menu interface designed by the master:
@ echo off
Cls
Title Ultimate Multi-function repair
: menu
Cls
Color 0A
Echo.
Echo = =
Echo, please select the operation you want to perform, and then press enter
Echo = =
Echo.
Echo 1. Network repair and Internet related settings, repair IE, custom blocking website
Echo.
Echo 2. Virus kill tool, port closed tool, turn off automatic playback
Echo.
Echo 3. Clear all redundant self-starting items and fix system errors
Echo.
Echo 4. Clean up the garbage of the system and improve the startup speed
Echo.
Echo Q. Quit
Echo.
Echo.
: cho
Set choice=
Set / p choice= Please select:
IF NOT "% choice%" = "" SET choice=%choice:~0,1%
If / I "% choice%" = = "1" goto ip
If / I "% choice%" = = "2" goto setsave
If / I "% choice%" = = "3" goto kaiji
If / I "% choice%" = = "4" goto clean
If / I "% choice%" = = "Q" goto endd
Invalid echo selection, please re-enter
Echo.
Goto cho
As long as you finish the previous chapters of this tutorial, the above program should be able to understand.
Second, if... Else... Conditional statement
As mentioned earlier, DOS conditional statements are mainly in the following forms
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
Enhanced usage: IF [/ I] string1 compare-op string2 command
Add / I to the enhanced usage and it is not case-sensitive!
There are also some symbols used to judge numbers in enhanced usage:
EQU-equals
NEQ-not equal to
LSS-less than
LEQ-less than or equal to
GTR-greater than
GEQ-greater than or equal to
The above command commands can all use parentheses to use a combination of multiple commands, including the else clause, in which conditional or loop commands can be nested.
For example:
IF EXIST filename (
Del filename
) ELSE (
Echo filename missing
)
It can also be written as:
If exist filename (del filename) else (echo filename missing)
However, this writing method is not suitable for the use of too many commands or nested commands. Note: else must be on the same line as if or the last parenthesis of if, such as:.) ELSE (. In parentheses, the newline program thinks it is a statement.
III. Circular statement
1. Specify the number of cycles
FOR / L% variable IN (start,step,end) DO command [command-parameters]
Combine commands:
FOR / L% variable IN (start,step,end) DO (
Command1
Command2
……
)
2. Execute a circular statement on a collection.
FOR% variable IN (set) DO command [command-parameters]
% variable specifies a parameter that can be replaced by a single letter.
(set) specify a file or group of files. You can use wildcards.
Commands executed by command on each file can be combined with multiple commands in parentheses.
FOR / R [[drive:] path]% variable IN (set) DO command [command-parameters]
Check the directory tree rooted in [drive:] path and point to the
FOR statement. If no directory is specified after / R, the current
Catalogue. If the set is only a single point (.) Character, the directory tree is enumerated.
As before, command can be combined in parentheses:
FOR / R [[drive:] path]% variable IN (set) DO (
Command1
Command2
……
Commandn
)
3. Conditional cycle
The above loop structure is implemented with the for command. The disadvantage of the for command loop is that the whole loop is treated as a command statement, which involves variable delay.
Using Goto statements and conditional judgment, dos can implement conditional loops. It's very simple. Take a look at the example:
Example:
@ echo off
Set var=0
The rem * cycle begins.
: continue
Set / a var+=1
Echo% var% secondary cycle
If var% lss 100 goto continue
Rem * cycle is over.
Echo loop execution completed
Pause
Example:
@ echo off
Set var=100
The rem * cycle begins.
: continue
Echo% var% secondary cycle
Set / a var-=1
If var% gtr 0 goto continue
Rem * cycle is over.
Echo loop execution completed
Pause
4. Subroutine
In batch programs, you can call external runnable programs, such as exe programs, or other batch programs, which can also be regarded as subroutines, but they are not convenient enough. If many programs are called, they are not concise and tedious.
In windowsXP, a batch can call a segment of this program, which is equivalent to a subroutine, which is usually placed after the main program.
Subroutine call format:
CALL: label arguments
Subroutine syntax:
: label
Command1
Command2
.
Commandn
Goto: eof
In the subroutine segment, the parameter% 0 refers to the label: label
The subprocedure is usually placed at the end, and pay attention to add exit or jump statement at the end of the main program to avoid mistakenly entering the subroutine.
The variables in the subroutine and the main program are global variables, and their scope is the entire batch program.
The parameters passed to the subroutine are specified in the call statement and called in the form of% 1,% 2 to% 9 in the subroutine, and the data returned by the subroutine only needs to be referenced directly after the call is over. Of course, you can also specify the return variable, see the following example.
Subroutine example 1:
@ echo off
Call: sub return
Return value of echo subroutine:% return%
Pause
Goto: eof
: sub
Set% 1 = Hello
Goto: eof
Running result: Hello
Subroutine example 2: design a subroutine for the addition of multiple integers
@ echo off
Set sum=0
Call: sub 10 20 35 40 50
Echo data summation result:% sum%
Pause
Goto: eof
: sub
Parameter 1 rem returns the name of the variable
Set / a sum+=%1
Shift / 1
If not "% 1" = "" goto sub
Goto: eof
Running result: 155
Fifth, use ftp command to realize automatic download
Ftp is a commonly used download tool. There are more than 40 commonly used commands in the ftp interface. I have learned it myself and will not introduce it. This paper introduces how to call the ftp command with the dos command line to realize the automatic login of ftp, upload and download, and automatically exit the ftp program.
You can actually save the ftp command combination as a text file, and then invoke it with the following command.
Ftp-n-s: [[drive:] path] filename
The above filename is the ftp command file, including login IP address, user name, password, operation command, etc.
Example:
Open 90.52.8.3 # Open ip
User iware # user is iware
Password8848 # password
Bin # binary transfer mode
Prompt
Cd tmp1 # change to the tmp1 directory under the iware user
Pwd
Lcd d:\ download # local directory
Mget * # download all files in the tmp1 directory
Bye # exit ftp
6. Use 7-ZIP to realize command line compression and decompression.
Syntax format: (see 7-zip help file for details, you can skip dizziness and learn again)
7z [...] [...]
Each command of 7z.exe has different parameters. Please see the help file.
Is the compressed package name
Is the file name, and wildcards or file lists are supported
Where 7z is the command line compression and decompression program 7z.exe, which is a command included in 7z.exe, listed as follows:
A: Adds files to archive. Add to compressed package
A command available parameters:
-I (Include)
-m (Method)
-p (Set Password)
-r (Recurse)
-sfx (create SFX)
-si (use StdIn)
-so (use StdOut)
-ssw (Compress shared files)
-t (Type of archive)
-u (Update)
-v (Volumes)
-w (Working Dir)
-x (Exclude)
B: Benchmark
D: Deletes files from archive. Delete files from the zip file
The available parameters of the d command:
-I (Include)
-m (Method)
-p (Set Password)
-r (Recurse)
-u (Update)
-w (Working Dir)
-x (Exclude)
E: Extract unzips the file to the current directory or specified directory
The available parameters of the e command are:
-ai (Include archives)
-an (Disable parsing of archive_name)
-ao (Overwrite mode)
-ax (Exclude archives)
-I (Include)
-o (Set Output Directory)
-p (Set Password)
-r (Recurse)
-so (use StdOut)
-x (Exclude)
-y (Assume Yes on all queries)
L: Lists contents of archive.
T: Test
U: Update
X: eXtract with full paths unzips the file to the current directory or specified directory with the full path of the file
The available parameters of the x command are:
-ai (Include archives)
-an (Disable parsing of archive_name)
-ao (Overwrite mode)
-ax (Exclude archives)
-I (Include)
-o (Set Output Directory)
-p (Set Password)
-r (Recurse)
-so (use StdOut)
-x (Exclude)
-y (Assume Yes on all queries)
7. Call VBScript program
Using the Windows script host, you can run scripts from a command prompt. CScript.exe provides command line switches for setting script properties.
Usage: CScript script name [script options.] [script parameters.]
Options:
/ / B batch mode: no script errors and prompts are displayed
/ / D enable Active Debugging
/ / E:engine uses the engine that executes the script
/ / H:CScript changes the default script host to CScript.exe
/ / H:WScript changes the default script host to WScript.exe (default)
/ / I interaction mode (default, as opposed to / B)
/ / Job:xxxx performs a WSF job
/ / Logo display logo (default)
/ / Nologo does not display logos: no flags are displayed during execution
/ / S saves the current command line options for this user
/ / T:nn timeout setting seconds: the maximum time allowed for a script to run
/ / X executes the script in the debugger
/ / U denotes the redirected Imax O from the console with Unicode
Script name is the name of a script file with an extension and required path information, such as d:/admin/vbscripts/chart.vbs.
Script options and parameters are passed to the script. The script parameter is preceded by a slash (/). Each parameter is optional; however, script options cannot be specified without a script name specified. If no parameters are specified, CScript displays CScript syntax and valid host parameters.
Convert a batch to an executable file
Because a batch file is a text file, anyone can edit it casually, which will destroy the commands inside, so if you convert it to an executable file in .com format, not only the execution efficiency will be greatly improved. and will not destroy the original function, but also can raise the priority to the highest level. Bat2Com can do this conversion work.
Knowledge: in the DOS environment, the priority of executable files from high to low is .com > .exe > .bat > .cmd, that is, if there are four types of files with the same file name in the same directory, when only typing the file name, DOS executes name.com, if you need to execute the other three files, you must specify the full name of the file, such as name.bat.
This is a free green tool that is only 5.43K in size and can be run on the command line of a pure DOS or DOS window. Usage: Bat2Com
FileName, which generates an executable file named FileNme.com in the same directory, and executes in the same way as the original .bat file.
IX. Time delay
Refer to [Hero] tutorial in this article
What is time delay? As the name implies, the execution of one command is delayed for a period of time before the next command is executed.
For the application of delay, see the following section: "Simulation Progress Bar".
1. Delay by using ping command
Example:
@ echo off
Before echo delay:% time%
Ping / n 3 127.0.0.1 > nul
After echo delay:% time%
Pause
Explanation: the "/ n" parameter of the ping command is used to indicate how many requests to send to the specified ip. In this example, three requests are sent to the native ip (127.0.0.1). 127.0.0.1 can be abbreviated to 127.1. "> nul" is to block out what is displayed by the ping command.
2. Delay by using for command
Example:
@ echo off
Before echo delay:% time%
For / l I in (1meme 1mem5000) do echo I > nul
After echo delay:% time%
Pause
Explanation: the principle is very simple, that is, to achieve the purpose of delay by using a count loop and shielding what it shows.
3. Using the vbs delay function, the accuracy is millisecond and the error is less than 1000 milliseconds.
Example:
Echo offecho% time%call: delay 5000echo% time%pauseexit:delayecho WScript.Sleep% 1 > delay.vbsCScript / / B delay.vbsdel delay.vbsgoto: eof
The run shows:
10:44:06.45
10:44:11.95
Please press any key to continue. . .
The above running results show that the actual delay is 5500 milliseconds, and the extra 500 milliseconds takes time to create and delete temporary files. The error is within a second.
4. Only batch commands are used to achieve arbitrary time delay with an accuracy of 10 milliseconds and an error of less than 50 milliseconds.
Deferred operations can be achieved with only batch commands.
Example:
@ echo off
Set / p delay= Please enter the number of milliseconds to delay:
Set TotalTime=0
Set NowTime=%time%
:: start time for reading. The format of the time is: 13pur01purl 05.95.
Echo program start time:% NowTime%
: delay_continue
Set / a minute1=1%NowTime:~3,2%-100
:: the number of minutes to read the start time
Set / a second1=1%NowTime:~-5,2%%NowTime:~-2%0-100000
:: change the number of seconds of the start time to milliseconds
Set NowTime=%time%
Set / a minute2=1%NowTime:~3,2%-100
:: read the number of minutes of the current time
Set / a second2=1%NowTime:~-5,2%%NowTime:~-2%0-100000
:: change the number of seconds of the current time to milliseconds
Set / a TotalTime+= (% minute2%-%minute1%+60)%% 60560000% second2% use% second1%
If TotalTime% lss delay% goto delay_continue
Echo program end time:% time%
Echo set delay time:% delay% milliseconds
Echo actual delay time:% TotalTime% milliseconds
Pause
The run shows:
Please enter the number of milliseconds to delay: 6000
Start time of the program: 15Rd 32RL 16.37
End time of the program: 15Rd 32RL 22.37
Set delay time: 6000 Ms
Actual delay time: 6000 Ms
Please press any key to continue. . .
The principle of implementation: first set the number of milliseconds to delay, and then accumulate the time with a loop until the cumulative time is greater than or equal to the delay time.
Error: windows system time can only be accurate to 10 milliseconds, so there may be a 10 millisecond error in theory.
After testing, when the delay time is more than 500 milliseconds, the above delay program generally has no error. When the delay time is less than 500 milliseconds, there may be tens of milliseconds error. Why? Because the delay program itself has running time, and the system time can only be accurate to 10 milliseconds.
For ease of reference, change the above example to the form of subroutine invocation:
@ echo off
Echo program start time:% Time%
Call: delay 10
Echo actual delay time:% totaltime% milliseconds
Echo program end time:% time%
Pause
Exit
::-the following is a delay subroutine
: delay
@ echo off
If "% 1" = "" goto: eof
Set DelayTime=%1
Set TotalTime=0
Set NowTime=%time%
:: start time for reading. The format of the time is: 13pur01purl 05.95.
: delay_continue
Set / a minute1=1%NowTime:~3,2%-100
Set / a second1=1%NowTime:~-5,2%%NowTime:~-2%0-100000
Set NowTime=%time%
Set / a minute2=1%NowTime:~3,2%-100
Set / a second2=1%NowTime:~-5,2%%NowTime:~-2%0-100000
Set / a TotalTime+= (% minute2%-%minute1%+60)%% 60560000% second2% use% second1%
If TotalTime% lss DelayTime% goto delay_continue
Goto: eof
10. Simulation progress bar
Here is a program to simulate the progress bar. If you apply it to your own program, you can make your program more beautiful.
@ echo off
Mode con cols=113 lines=15 & color 9f
Cls
Echo.
The echo program is initializing. . .
Echo.
Echo ┌──┐
Set/p= ■ nul / N1 & set/p= run-> enter cmd-> edit-> ctrl+p (meaning special characters are allowed)-> press ctrl+a to display the smiley face pattern.
(if you want to continue entering special characters, press ctrl+p again, and then ctrl+ a letter)
The above is the input method of special characters, selected from the Hero tutorial, it is very useful. That is, use the editor program edit to enter special characters, then save them as a text file, then open the file under windows and copy the special symbols in it.
Some simple special symbols can be entered directly in the dos command window and saved as a text file with redirection.
Example:
C: > ECHO ^ G > temp.txt
"^ G" is entered with Ctrl+G or Alt+007 (after holding down Alt, you can only press the number of the keypad). Entering more than one ^ G can produce multiple tones.
The application of special characters is also very interesting. Here is just one example: backspace key (input method: start-> run-> enter cmd-> edit-> ctrl+p-> backspace key)
The Backspace key means to delete the character on the left. This key cannot be entered normally in the document, but can be typed and copied through the edit editor. That is, "".
Using the backspace key, combined with space coverage, you can design the flickering text effect.
Example: text flashes, you can use the Ctrl+C key combination to force the final run
@ echo off
: start
There is a bright moonlight nul in front of set/p= 's bed.
:: set delay time
Set / p a=nul
:: set delay time
Set / p a = nul
Exit
: hero
For / l% k in (1mem1mem10) do (
Ping / n 0 127.0.0.1 > nul
Set / p a =
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.