[转载]Bat CMD 批处理文件脚本总结(英文)

1.               Overview

1.1.    .bat: The first extension used by Microsoft for batch files. This extension can be run in most Microsoft Operating Systems, including MS-DOS and most versions of Microsoft Windows.

1.2.    .cmd: Designates a Windows NT Command Script, which is written for the Cmd.exe shell, and is not backward-compatible with COMMAND.COM.

1.3.    The only known difference between .cmd and .bat file processing is that in a .cmd file the ERRORLEVEL variable changes even on a successful command that is affected by Command Extensions (when Command Extensions are enabled), whereas in .bat files the ERRORLEVEL variable changes only upon errors.

 

2.               @echo off/echo on

1. “echo” is used to display messages on console screen.

2. “echo.” Is used to display a empty line.

3. “echo off”: Only display the command output on screen without command name.

4. “echo on”: It is the default setting. Display the command and all outputs.

5. “echo”: When execute echo alone, it will display the echo status like “ECHO is on” or “ECHO is off”.

6. “@”:@ symbol is the same as ECHO OFF applied to the current line only. The command name will not show when use @ sysmbol.

3.               SETLOCAL/ENDLOCAL

1. SETLOCAL is used to control the visibility of environment variables in a batch file. If a batch script does not use SETLOCAL and ENDLOCAL then all variables will be Global, visible and modifiable by other scripts.

@echo off

setlocal

set version=1.0

echo %version%

endlocal

echo Show %version%

::The follow is global variable

set version=2.0

echo %version%

2. EnableDelayedExpansion. Help link.

Normally batch files will expand environment variables once for each command/line.

Code

Output

@echo off

setlocal

set var=test & echo show %var%

endlocal

show

@echo off

Setlocal ENABLEDELAYEDEXPANSION

set var=test & echo show !var!

endlocal

show test

@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

With ENABLEDELAYEDEXPANSION, the caret ^ escapes each special character all the time, not just for one command. This makes it possible to work with HTML and XML formatted strings in a variable.

SETLOCAL

Set _html= Hello^>World.text

Echo %_html%

ENDLOCAL

SETLOCAL EnableDelayedExpansion

Set _html= Hello^>World.text

Echo !_html!

ENDLOCAL

SETLOCAL EnableDelayedExpansion

Set _html=html format: ^<title^>Hello world^</title^>

Echo !_html!

ENDLOCAL

3. DISABLEEXTENSIONS.

    Command extension doesn’t mean file expanded-name. You can use “/F” parameter for “For loop” statement.

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

    Command Extensions are enabled by default. With DISABLEEXTENSIONS,

4.               Set

1. Use SET without parameters: display all environment variables of the current user.(set)

2. Use SET with a variable name: display all environment variables begin with that name. (set PROCESSOR)

3. SET variable=string: Assign a text string to the variable.

4. SET “”: Display undocumented variables. (echo %=C:%)

5. SET “var=”(or SET var=): Delete a variable name.

6. SET /A variable=expression: Use arithmetic operation to assign value.

()                  - grouping

! ~ -               - unary operators

* / %               - arithmetic operators

+ -                 - arithmetic operators

<< >>               - logical shift

&                   - bitwise and

^                   - bitwise exclusive or

|                   - bitwise or

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

 &= ^= |= <<= >>=

                  ,                   - expression separator

7. SET /P variable=[promptString]: Prompt for user input. The PromptString is displayed before the user input is read. The PromptString can be empty.

The CHOICE command is an alternative to SET /P.

@echo off

SETLOCAL

set /p version=Please enter the Pangaea version:

echo you will install Pangaea %version%

endlocal

8. Useful environment variable.

%CD% - expands to the current directory string.

%DATE% - expands to current date using same format as DATE command.

%TIME% - expands to current time using same format as TIME command.

%RANDOM% - expands to a random decimal number between 0 and 32767.

5.               Choice

1. Detailed.

CHOICE [/C choices] [/N] [/CS] [/T timeout /D choice] [/M text]

Description:

This tool allows users to select one item from a list of choices and returns the index of the selected choice.

NOTE:

The ERRORLEVEL environment variable is set to the index of the key that was selected from the set of choices. The first choice listed returns a value of 1, the second a value of 2, and so on. If the user presses a key that is not a valid choice, the tool sounds a warning beep. If tool detects an error condition, it returns an ERRORLEVEL value of 255. If the user presses CTRL+BREAK or CTRL+C, the tool returns an ERRORLEVEL value of 0. When you use ERRORLEVEL parameters in a batch program, list them in decreasing order.

/C    choices

 /N

 /CS

 /T    timeout

 /D    choice

 /M    text

 

Specifies the list of choices to be created.

Default list is "YN".

Hides the list of choices in the prompt.The message before the prompt is displayed and the choices are still enabled.

Enables case-sensitive choices to be selected.

By default, the utility is case-insensitive.

 The number of seconds to pause before a default choice is made. Acceptable values are from 0 to 9999. If 0 is specified, there will be no pause and the default choice is selected.

Specifies the default choice after nnnn seconds. Character must be in the set of choices specified by /C option and must also specify nnnn with /T.

Specifies the message to be displayed before the prompt. If not specified, the utility displays only a prompt.

2. Example.

@echo off

SETLOCAL

CHOICE /C ADL /M "Press A for Administrator, D for Domain user or L for Local user."

IF %errorlevel%==1 goto :Admin

IF %errorlevel%==2 goto :Domain

IF %errorlevel%==3 goto :Local

goto Exit

:Admin

echo You are a administartor

goto Exit

:Domain

echo You are a Domain user

goto Exit

:Local

echo You are a Local user

goto Exit

:Exit

endlocal

6.               Rem and Arguments.

1. REM [comment]: Records comments (remarks) in a batch file. You can use “::” instead of REM.

2. Arguments.

Test.cmd

1

2

3

4

5

6

7

8

9

n

255

%0

%1

%2

%3

%4

%5

%6

%7

%8

%9

%n

%255

3. Filename Parameter Extensions.

When a parameter is used to supply a filename then the following extended syntax can be applied. We are using the variable %1 (but this works for any parameter)

%~f1 - expands %1 to a Fully qualified path name.
%~d1 - expands %1 to a Drive letter only.
%~p1 - expands %1 to a Path only.
%~n1 - expands %1 to a file Name, or if only a path is present (with no trailing backslash\) - the last folder in that path
%~x1 - expands %1 to a file eXtension only - .txt
%~s1 - changes the meaning of f, n and x to reference the Short name (see note below)
%~1 - expand %1 removing any surrounding quotes (")
%~a1 - display the file attributes of %1
%~t1 - display the date/time of %1
%~z1 - display the file size of %1

%~$PATH:1 - search the PATH environment variable and expand %1 to the fully qualified name of the first match found.

The modifiers above can be combined:

%~dp1 - expands %1 to a drive letter and path only

%~nx2 - expands %2 to a file name and extension only

::Test.bat

::Example: test.bat test.bat

@echo off

SETLOCAL

set fn=%~f1

echo %fn%

endlocal

7.               IF statement.

1. Detailed.

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         : Do a case Insensitive string comparison.

compare-op :

            EQU : equal

NEQ : not equal

LSS : less than

LEQ : less than or equal

GTR : greater than

GEQ : greater than or equal

2. Example.

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.

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

 

Options:

eol=c           - specifies a line comment character.

skip=n         - specifies the number of lines to skip at the beginning of the file.

delims=xxx      - specifies a delimiter set. This replaces the default delimiter

                           set   of space and tab.

tokens=x,y,m-n - specifies which tokens from each line are to be passed

                             to the for body for each iteration.

usebackq      - allows use double quotes to quote file names in filenameset.

 

Note:

If you are using the FOR command at the command line rather than in a batch program, specify %parameter instead of %%parameter. Variable names are case sensitive, so %g is different from %G.

(set)      Specifies a set of one or more files. Wildcards may be used.

2. Example.

@echo off

SETLOCAL

for %%G in (*.bat *.txt) do echo %%G

endlocal

9.               Net.

1. Manage Services: Net start, stop, pause, continue [service].

2. Connect to a file/print share(Drive Map):Net use.

    NET USE [driveletter:] \\ComputerName\ShareName[\volume] [password] [/USER:[Domain\]UserName]

    NET USE drvieletter: /delete

3. Net share: Display all local share.

4. Net share ShareName: Display the share info of ShareName.

5. Create a local file share: NET SHARE sharename=drive:path /REMARK:"text" [/CACHE:Manual | Automatic | No ]

6. Change user limited number and edit remark:

    NET SHARE sharename /USERS:number /REMARK:"text"

    NET SHARE sharename /UNLIMITED /REMARK:"text"

7. Delete a share: NET SHARE {sharename | devicename | drive:path} /DELETE

8. Net view \\ComputerName: List all shares on a remote computer.

9. Net localgroup: net localgroup administrators fareast\esdcvsec /add

10. Rename a computer: netdom renamecomputer SourceName /newname:TargetName [/UserD:user [/PasswordD:[password]]]

11. Join in a domain: net dom join ComputerName /domain: fareast.corp.microsoft.com /UserD:esdcvsec /PasswordD:123456

10.         Reference

1. http://ss64.com/nt/

原文地址:https://www.cnblogs.com/eastson/p/1658948.html