Bat cmd Batch File Script Summary

Source: Internet
Author: User
Tags arithmetic operators administrator password

1. Summary

(1). ". Bat": This is the suffix of Microsoft's first batch of processed files and can be run in almost all Windows operating systems.

(2). ". cmd": it is a command line script designed for Windows NT. It is designed for cmd.exe shell and does not have backward compatibility with command. com.

(3) what is currently known. CMD and. the difference in the BAT file is the change to the errorlevel variable: When the command extensions (command line extension) is in the Enabled state, even if it is. A successfully executed command in the CMD file can change the value of errorlevel. in the BAT file, the errorlevel variable is changed only when an error occurs.

2. @ echo off/echo on

(1). "Echo" is used to display information on the console.

(2). "Echo." is used to display an empty row. (Note: There is no space between the ECHO and the vertices in the lower right corner. If there is a space, the periods are displayed .)

(3). "echo off": After this command is used, other commands only display the command results, rather than the command itself.

(4). "echo on": This is the default value, indicating that all command results and command lines are displayed.

(5 ). "Echo": When Echo is executed without any parameters, the status of ECHO is displayed: "Echo is on" or "Echo is off ".

(6). "@": @ indicates that the command itself of the current line is not displayed. If only echo off is used, although the command after echo off is not displayed, only the command result is displayed, but echo off is indeed displayed, this is why @ echo off is used.

3. setlocal/endlocal

(1). SETLOCAL is used to control the visibility of variables in the batch files. It is a local variable that is often used in advanced languages. All variables between SETLOCAL and ENDLOCAL are local, so that the value of the variable is not changed by other script files. All variables that do not use this label are Global visible ), may be changed by other files. The example below demonstrates this point.

@echo off
setlocal 
set version=1.0
echo the first version is %version%
endlocal
echo the second version is %version%
::The follow is global variable
set version=2.0
echo the third version is %version%
Execute this file and output:

 

the first version is 1.0
the second version is
the third version is 2.0

The second version is a global variable but is not defined, so it is a null value. Execute again:

the first version is 1.0
the second version is 2.0
the third version is 2.0

@echo off
setlocal 
set version=1.0
echo the first version is %version%
endlocal
echo the second version is %version%
::The follow is global variable
set version=5.0
echo the third version is %version%
Run the second file:

 

the first version is 1.0
the second version is 2.0
the third version is 5.0

Execute again:

the first version is 1.0
the second version is 5.0
the third version is 5.0

It can be seen that the scope of the variable is still very careful in the simple batch processing file, otherwise it can cause ever-changing results, so this script is very unstable. Therefore, the variable scope is very important.

(2). EnableDelayedExpansion. (See Baidu: http://baike.baidu.com/view/2923132.htm)

Code

 

Result

@echo off
setlocal
set var=test & echo show %var%
endlocal

 

Show

When % var % is parsed, CMD has not executed any statements, so the system does not know the variable, so it is considered that the variable is not defined, so it shows a null value.

@echo off
Setlocal ENABLEDELAYEDEXPANSION
set var=test & echo show !var!
endlocal

 

Show Test

Variable latency extension is used! VaR !, In fact, this variable is not recognized during execution, but after this statement is executed, the return value is assigned. The Variable Delay extension is used for post-processing.

 

The for statement seems to have written many rows, which is actually considered as a statement. Therefore, if the variable delay extension is not used, every row in the for statement only remembers what the system remembers. After Variable Delay extension is used, the entire statement is executed, and the value is assigned after "event processing" before being displayed on the console. The following example illustrates the problem.

@echo off
setlocal
:: count to 5
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [%_tst%] & set /a _tst+=1)
echo Total = %_tst%
[0]
[0]
[0]
[0]
[0]
Total = 5
@echo off
setlocal
:: count to 5
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [!_tst!] & set /a _tst+=1)
echo Total = !_tst!
[0]
[1]
[2]
[3]
[4]
Total = 5
     

In CMD, the system uses "^" as the escape character. After the variable delay extension ENABLEDELAYEDEXPANSION is used, the escape character ^ can always be used, instead of being limited to one command line. In this way, it is much easier to process characters in HTML and XML format. See the following example.

@ Echo off

The REM file creates world.txt to the local disk. The file content is Hello.

REM, that is, during the second operation, the escape character does not play a role.

SETLOCAL 
Set _html= Hello^>World.txt
Echo %_html%
ENDLOCAL

@ Echo off

This file will output Hello> World.txt, which will take effect all the time.

SETLOCAL EnableDelayedExpansion
Set _html= Hello^>World.txt
Echo !_html!
ENDLOCAL
@echo off

REM uses variable latency extension to process html statements.

SETLOCAL EnableDelayedExpansion
Set _html=html format: ^<title^>Hello world^</title^>
Echo !_html!
ENDLOCAL

(3). DISABLEEXTENSIONS.

It is worth noting that the extension here is not the extension, but the extension function of the command. For example, the "/F" parameter is the command extension of the For loop.

The following statement can be executed only when command extension is used.

FOR/F "DELIMS =" % a IN (test. TXT) DO @ echo %

Otherwise, we need to output a file. We can only use Type test.txt. Command extension is enabled by default.

4. Set

(1). SET without any parameters: All system environment variables of the current user are displayed. (Set)

(2). SET with a variable name: Search and display the environment variable starting with this variable name. (Set PROCESSOR will display the variables starting with PROCESSOR)

(3). SET variable = string: assign a value to a variable.

(4). SET "": use an empty pair of double quotation marks to display a variable that is not displayed without parameters. Here I will show two strange variables.

= C: \ Users \ Lingli

= E: \ Powershell

You can use cd % = C: % To Go To The C: \ Users \ Lingli directory.

(5). SET "var =" (or SET var =): delete a variable.

(6). SET/A variable = expression: assign values to variables using Arithmetic Operators.

()-Combination

! ~ --Unary operator

*/%-Arithmetic Operator

+--Arithmetic Operator

<>-Logical offset

&-Bit and

^-Bitwise OR

|-Bit or

= * =/= % = + =--Value assignment

<=>>=

(7). Set/P variable = [prompt character]: prompt the user to enter and assign the input value to variable. The prompt character can be blank. Sometimes choice can be used instead of set/P.

@echo off
setlocal
set /p version=Please enter the QQ version:
echo you will install QQ %version%
endlocal

(8). Useful environment variables.

% Cd %-current path name.

% Date %-current date.

% Time %-current time.

% Random %-displays a random number between 0 and 32767. You can see that cmd can also obtain random numbers.

5. Choice

(1). Detailed Syntax:

 

Choice [/C choices] [/n] [/CS] [/T timeout/d choice] [/M text]

This command provides a user selection list and uses the errorlevel parameter to return the sequence number of the selected item. For 1, for 2, and so on, if you press Ctrl + C to exit without selecting, 0 is returned.

/C choices

 

/N

/CS

/T timeout

/D choice

/M text

Use letters to list the provided options. The default value is "YN", that is, and no.

 

Hide the selection list. If this option is used, the following is clearly written in the prompt text. It is not recommended.

Enable case sensitivity. The default value is case insensitive.

Select timeout settings.

Default options after timeout.

Prompt characters. It is best to clarify the question to be selected.

(2). Example:

@ Echo off
Setlocal
Choice/c abc/M "select Login User: A-administrator, B domain user, C registered user"
If % errorlevel % = 1 Goto: Admin
If % errorlevel % = 2 Goto: domain
If % errorlevel % = 3 Goto: Local
Goto exit
 
: Admin
Echo welcome Administrator
Goto exit
 
: Domain
Echo welcome Domain Users
Goto exit
 
: Local
Echo welcome to registered users
Goto Exit
 
: Exit
Endlocal

6. REM and arguments.

(1). Rem [comment]: Annotation of the batch file. You can use ":" To replace REM.

(2). parameters.

% 0 corresponds to the file name, and the others correspond to one parameter value. 255 parameters are supported.

Test. cmd 1 2 3 ... N ... 255
% 0 % 1 % 2 % 3 ... % N ... % 255

(3). Extension of file name parameters.

When using a file name as a parameter, you can use the following file name extension. In the following example, % 1 is extended. In fact, all parameters can be extended similarly.

% ~ F1-extension % 1 is the full name with path.
% ~ D1-only display the disk name.
% ~ P1-only the file path is displayed.
% ~ N1-only display the file name, excluding the suffix and path.
% ~ X1-only show the suffix.
% ~ S1-change to a short file name, which will contain "~" Symbol.
% ~ 1-if the file name contains spaces, double quotation marks are added to the file name. This function removes double quotation marks.
% ~ A1-display file attributes.
% ~ T1-display the file modification time.
% ~ Z1-displays the file size.
 

The above extensions can be combined:

% ~ Dp1-extended % 1 is the disk name and path name.

% ~ Nx2-extension % 2 is the file name and file suffix.

::Test.bat
::Example: test.bat test.bat
@echo off
setlocal
set fn=%~f1
echo %fn%
endlocal

7. IF statement

(1). Detailed Syntax:

File syntax   
IF [NOT] EXIST filename command 
IF [NOT] EXIST filename (command) ELSE (command)
 
String syntax   
IF [/I] [NOT] item1==item2 command 
IF [/I] item1 compare-op item2 command
IF [/I] item1 compare-op item2 (command) ELSE (command)
 
Error Check Syntax
IF [NOT] DEFINED variable command
IF [NOT] ERRORLEVEL number command 
IF CMDEXTVERSION number command

Key

/I: The file name is case-insensitive when compared.

Compare-op: logical comparison

EQU: equal

NEQ: not equal is not equal

LSS: less

LEQ: less than or equal is less than or equal

GTR: greater

GEQ: greater than or equal is greater than or equal

(2). Example (we can see that the If statement is also a statement)

If exist filename (del filename) ELSE (echo The file was not found .)

IF EXIST filename (
del filename
) ELSE ( 
echo The file was not found.
)

8. For Loop

(1). Detailed Syntax:

FOR-Files
FOR %%parameter IN (set) DO command 
 
FOR-Files-Rooted at Path   
FOR /R [[drive:]path] %%parameter IN (set) DO command 
 
FOR-Folders
FOR /D %%parameter IN (folder_set) DO command 
 
FOR-List of numbers   
FOR /L %%parameter IN (start,step,end) DO command 
 
FOR-File contents   
FOR /F ["options"] %%parameter IN (filenameset) DO command 
FOR /F ["options"] %%parameter IN ("Text string to process") DO command
 
FOR-Command Results 
       FOR /F ["options"] %%parameter IN ('command to process') DO command

Eol = c-line first annotator. If this annotator exists, this line is not processed.

Skip = n-the first n rows are skipped and not processed

Delims = xxx-delimiter set. The default Delimiter is space and Tab.

Tokens = x, y, m-n-which is used for cyclic operations.

Usebackq-when the file name contains spaces that require double quotation marks, usebackq is used to process the content in double quotation marks as a file; otherwise, it is processed as a string.

Note:

In the batch file, % parameter is used for parameters. When you get the command line, % parameter is a percent difference. Variable names are case sensitive, so % g and G are different.

(Set) indicates a collection of files, one or more files, you can also use wildcards for file names.

(2). Example:

@echo off
setlocal
for %%G in (*.bat *.txt) do echo %%G
endlocal

9.net.

(1). Management service: Net start, stop, pause, and continue [service].

(2) connect to a shared file: Net use.

Net use [disk name:] \ shared name [\ subdirectory name] [Password] [/USER: [Domain Name \] USER name]

Net use disk name:]:/delete

(3). Net share: displays all local shares, including hidden shares.

(4). Net share ShareName: displays the shared information.

(5) create a local SHARE: net share sharename = drive: path/REMARK: "text" [/CACHE: Manual | Automatic | No]

(6) modify the user quantity limit and Mark.

Net share sharename/USERS: number/REMARK: "text"

NET Share sharename/unlimited/remark: "text"

(7). Delete share: net share {sharename | devicename | drive: path}/delete

(8). Net view \ computer name: lists all sharing of remote machines.

(9). Net localgroup: add an account to a local group. For example, add an account to the Administrator group: Net localgroup administrators domainname \ Username/Add

(10). Rename the machine: netdomrenamecomputer original machine name/newname: Modified machine name/userd: User/passwordd: Password

(11). Add domain: Net Dom join computer name/domain: domain name/userd: domain administrator account/passwordd: domain administrator password

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.