Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write BAT script

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to write a BAT script for you. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Echo, @, call, pause, rem (tip: use:: instead of rem) are the most commonly used commands for batch files, so let's start with them.

Echo indicates the characters after this command is displayed

Echo off means that all commands that run after this statement do not display the command line itself

@ is similar to echo off, but it is added to the front of each command line, indicating that the command line is not displayed at run time (only the current line is affected).

Call calls another batch file (if you call another batch file directly without call, you will not be able to return the current file and execute subsequent commands for the current file after executing that batch file).

Pause running this sentence pauses the execution of the batch and displays Press any key to continue... on the screen Wait for the user to press any key before continuing

Rem indicates that the characters after this command are interpretation lines (comments), which are not executed, but are only for future reference (equivalent to comments in the program).

Example 1: edit the a.bat file with edit, enter the following contents and save it to c:\ a.bat. After executing the batch file, you can write all the files in the root directory to a.txt, start UCDOS, enter WPS and other functions.

The contents of the batch file are as follows: command comments:

@ echo off does not display subsequent command line and current command line

Dir c:\ *. * > a.txt writes the list of files on disk c to a.txt

Call c:\ ucdos\ ucdos.bat calls ucdos

Hello, echo. Display "Hello".

Pause pauses and waits for the button to continue

Rem ready to run wps Note: prepare to run wps

Cd ucdos enters the ucdos directory

Wps runs wps

Parameters for batch files

Batch files can also use parameters like C language functions (equivalent to command-line arguments for DOS commands), which requires a parameter representation of "%".

% [1-9] represents a parameter, which is a string separated by a space (or Tab) after the file name when running a batch file. Variables can range from% 0 to% 9jue% 0 to represent the batch command itself, and other parameter strings are represented in the order of% 1 to% 9.

Example 2 C: there is a batch processing file named f.bat in the root directory, which contains:

@ echo offformat 1

If you execute C:\ > f a:

Then when executing f.bat,% 1 represents a format, so format% 1 is equivalent to format a, so the above command is actually executed at run time:

Example 3 C: the batch processing file under the root directory is named t.bat, which contains:

@ echo offtype 1 type 2

Then run C:\ > t a.txt b.txt

% 1: indicates a.txt

% 2: indicates b.txt

So the above command will display the contents of the a.txt and b.txt files sequentially.

Special command

If goto choice for is a more advanced command in batch files, and if you are adept at using these commands, you are an expert in batch files.

First, if is a conditional statement, which is used to determine whether the specified conditions are met, thus deciding to execute different commands. There are three formats:

1. If [not] "Parameter" = = "string" Command to be executed

If the parameter is equal to the specified string (not for inequality, the same below), the condition holds, run the command, otherwise run the next sentence.

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

2. If [not] exist [path\] File name commands to be executed

If there is a specified file, 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.

3. Commands to be executed by if errorlevel

Many DOS programs will return a numeric value to represent the result (or status) of the program after running. The return value of the program can be judged by the if errorlevel command, and different commands must be executed according to different return values (the return values must be arranged in the order from largest to smallest). If the return value is equal to the specified number, the condition holds, run the command, otherwise run the next sentence.

Such as if errorlevel 2 goto x2

Second, when the goto batch file runs here, it will jump to the label specified by goto (the label is label, followed by a standard string to define). Goto statements are generally used in conjunction with if to execute different command groups according to different conditions.

Such as:

Goto end:end echo this is the end

The label is defined by ": string", and the line of the label is not executed.

Third, choice uses this command to allow the user to enter a character (for selection), so as to return different errorlevel according to the user's choice, and then cooperate with if errorlevel to run different commands according to the user's choice.

Note: choice commands provide external commands for DOS or Windows systems, different versions of choice command syntax will be slightly different, please use choice /? Check the usage.

Command syntax for choice (this syntax is the syntax for the choice command in Windows 2003, and the command syntax for other versions of choice is more or less the same):

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 create. The default list is "YN".

/ N hides the list of options in the prompt. Prompt that the previous message is displayed

The option is still enabled.

/ CS allows you to select case-sensitive options. By default, this tool

Regardless of case.

The number of seconds paused before / T timeout makes the default selection. Acceptable values are from 0

To 9999. If 0 is specified, there will be no pause, the default option

You'll get a choice.

/ D choice specifies the default option after nnnn seconds. Characters must be in use / C selection

Item; at the same time, nnnn must be specified with / T.

/ M text specifies the message to be displayed before the prompt. If not specified, the tool only

Displays prompts.

/? Displays a help message.

Note:

The ERRORLEVEL environment variable is set to the key index selected from the selection set. The first selection listed

The option returns 1, the second option returns 2, and so on. If the key pressed by the user is not a valid selection

The tool emits a warning sound. If the tool detects an error status, it returns 255

ERRORLEVEL value. If the user presses the Ctrl+Break or Ctrl+C key, the tool returns 0

The ERRORLEVEL value of the When using the ERRORLEVEL parameter in a batch program, lower the parameter

Arrange in order.

Example:

CHOICE /?

CHOICE / C YNC / M "press Y for confirmation, N for confirmation, or C for cancellation."

CHOICE / T 10 / C ync / CS / D y

CHOICE / C ab / M "Please select a for option 1 and b for option 2."

CHOICE / C ab / N / M "Please select a for option 1 and b for option 2."

If I run the command: CHOICE / C YNC / M, press Y to confirm, N to confirm, or C to cancel.

The screen displays:

Press Y for confirmation, N for confirmation, or C for cancellation. [Y,N,C]?

Example: the contents of test.bat are as follows (note that when you use if errorlevel to judge the return value, you should arrange the return value from high to low):

Echo off choice / C dme / M "defrag,mem,end" if errorlevel 3 goto endif errorlevel 2 goto mem if errotlevel 1 goto defrag:defrag c:\ dos\ defrag goto end:mem mem goto end:end echo good bye

After this batch is run, "defrag,mem,end [DJM me]?" will be displayed, and the user can select d me, and then the if statement will judge according to the user's choice. D means to execute the program segment labeled defrag, m means to execute the program segment labeled mem, e means to execute the program segment labeled end, and each program segment finally jumps the program to the end label with goto end, and then the program will display good bye. The batch run ends.

Fourth, the for loop command, as long as the conditions are met, it will execute the same command multiple times.

Syntax:

Execute a specific command for each file in a set of files.

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.

Command specifies the commands to be executed on each file.

Command-parameters

Specify parameters or command line switches for a specific command.

For example, there is a line in a batch file:

For% c in (* .bat * .txt) do type% c

The command line displays the contents of all files in the current directory with bat and txt extensions.

Batch processing example

1. IF-EXIST

1)

First, use notepad to create a test1.bat batch file in C:\, with the following contents:

@ echo off IF EXIST\ AUTOEXEC.BAT TYPE\ AUTOEXEC.BAT IF NOT EXIST\ AUTOEXEC.BAT ECHO\ AUTOEXEC.BAT does not exist

Then run it:

C:\ > TEST1.BAT

If an AUTOEXEC.BAT file exists in C:\, its contents will be displayed, and if it does not exist, the batch will prompt you that the file does not exist.

2)

Then create a test2.bat file with the following contents:

@ ECHO OFF IF EXIST\% 1 TYPE\% 1 IF NOT EXIST\% 1 ECHO\% 1 does not exist

Execute:

C:\ > TEST2 AUTOEXEC.BAT

The result of running the command is the same as above.

Description:

(1) IF EXIST is used to test the existence of files in the format of

IF EXIST [path + File name] command

(2)% 1 in the test2.bat file is a parameter, and DOS allows you to pass 9 batch parameter information to the batch file, which is% 1% 9 (% 0 represents the test2 command itself), which is a bit like the relationship between arguments and formal parameters in programming.% 1 is a formal parameter and AUTOEXEC.BAT is an actual parameter.

3) further, create a file called TEST3.BAT, which reads as follows:

@ echo offIF "% 1" = = "A" ECHO XIAO IF "% 2" = = "B" ECHO TIAN IF "% 3" = = "C" ECHO XIN

If you run:

C:\ > TEST3 A B C

The screen displays:

XIAO

TIAN

XIN

If you run:

C:\ > TEST3 A B

It will appear on the screen

XIAO

TIAN

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

2 、 IF-ERRORLEVEL

Create a TEST4.BAT with the following contents:

@ ECHO OFF

Failed to copy XCOPY C:\ AUTOEXEC.BAT D:IF ERRORLEVEL 1 ECHO file

IF ERRORLEVEL 0 ECHO successfully copied the file

Then execute the file:

C:\ > TEST4

If the file copy is successful, the screen displays "copy file successfully", otherwise "file copy failed" is displayed.

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

So the following batch file is incorrect:

ECHO OFF XCOPY C:\ AUTOEXEC.BAT D:\ IF ERRORLEVEL 0 ECHO successfully copied the file IF ERRORLEVEL 1 ECHO could not find the copy file IF ERRORLEVEL 2 ECHO user aborted copy operation through ctrl-c IF ERRORLEVEL 3 ECHO preset error prevented file copy operation IF ERRORLEVEL 4 ECHO copy error during copy

Regardless of whether the copy is successful or not, the following:

Copy file not found

The user aborts the copy operation through ctrl-c

Preset error prevents file copy operation

Write disk error during copy

Will be displayed.

Here are the return values of several commonly used commands and what they represent:

Backup

0 backup successful

1 backup file not found

2 File sharing conflicts prevent backups from being completed

3. Users abort backup with ctrl-c

4 the backup operation was aborted due to a fatal error

Diskcomp

0 disk is the same.

One set is different.

2 the user aborts the comparison operation through ctrl-c

3 the comparison operation is aborted due to a fatal error

4 comparison of preset error abort

Diskcopy

0 disk copy operation succeeded

1 non-fatal disk read / write error

2 the user ends the copy operation through ctrl-c

3 abort the copy of the disk due to a fatal processing error

4 preset error prevents copy operation

Format

0 formatted successfully

3 the user aborts the formatting process through ctrl-c

4 the format was aborted due to a fatal processing error

5 prompting "proceed with format (yzone)?" The next user types n to end.

Xcopy

0 successfully copied the file

1 copy file not found

2 the user aborts the copy operation through ctrl-c

4 preset error prevents file copy operation

5 disk writing error during copy

3. IF STRING1 = = STRING2

Create a TEST5.BAT. The file content is as follows:

@ echo off

IF "% 1" = = "A" formAT A:

Execute:

C:\ > TEST5 A

The content of whether to format the A: disk appears on the screen.

Note: in order to prevent the argument from being empty, it is common to enclose the string in double quotes (or other symbols, note that you cannot use reserved symbols).

For example: if [% 1] = = [A] or if% 1

5 、 GOTO

Create a TEST6.BAT. The file content is as follows:

@ ECHO OFF

IF EXIST C:\ AUTOEXEC.BAT GOTO _ COPY

GOTO _ DONE

: _ COPY

COPY C:\ AUTOEXEC.BAT D:\

: _ DONE

Note:

(1) the colon ":" before the label is the ASCII character. There can be no space between the colon and the label.

(2) the naming rules of labels are the same as those of file names.

(3) DOS supports labeling with a maximum of eight characters. When it is impossible to distinguish between two labels, it will jump to the nearest label.

6 、 FOR

Create C:\ TEST7.BAT. The file content is as follows:

@ ECHO OFF

FOR% C IN (* .BAT * .TXT * .SYS) DO TYPE% C.

Run:

C: > TEST7

After execution, the contents of all files under the root directory of C: disk with the extensions of BAT, TXT, and SYS will be displayed (excluding hidden files).

Use of the bat command

one。 A brief introduction to simple batch Internal commands

1. Echo command

Turn on or off the request echo feature, or display messages. If there are no parameters, the echo command displays the current echo settings.

Grammar.

Echo [{on off}] [message]

Sample:@echo off / echo hello world

In practical application, we will combine this command with redirection symbols (also known as pipe symbols, usually use > >) to input some commands into files of a specific format. This will be reflected in future examples.

2. @ command

Indicates that the commands after @ are not displayed, so during the invasion (such as using batch processing to format the enemy's hard drive), you will not be able to let the other party see the commands you are using.

Sample:@echo off

@ echo Now initializing the program,please wait a minite...

@ format X: / q/u/autoset (the / y parameter is not allowed in the format command. Fortunately, Microsoft left us an autoset parameter, and the effect is the same as / y.)

3. Goto command

Specify to jump to the label, and when the tag is found, the program will process the command that starts on the next line.

Syntax:

Goto label (label is a parameter that specifies the lines in the batch program to be directed to. )

Sample:

If {% 1} = = {} goto noparms

If {% 2} = {} goto noparms (if you don't understand the if,% 1,% 2 here, skip it first, and there will be a detailed explanation later. )

@ Rem check parameters if null show usage

: noparms

Echo Usage: monitor.bat ServerIP PortNumber

Goto end

The name of the tag can be chosen at will, but it is better to have a meaningful letter, preceded by a letter: to indicate that the letter is a label, and the goto command is based on this: 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.

4. Rem command

The comment command, which is equivalent to / *-/ in the C language, is not executed, but acts as a comment for others to read and you to modify later.

Rem Message

Sample:@Rem Here is the description.?

5. Pause command

When you run the Pause command, the following message is displayed:

Press any key to continue. . .

Sample:

@ echo off

: begin

Copy aRom back. * d:\

Echo Please put a new disk into driver A

Pause

Goto begin

In this example, all files on disk in drive An are copied to d:\ back. When the comment that appears prompts you to put another disk in drive A, the pause command suspends the program so that you can replace the disk and press any key to continue processing.

6. Call command

Calls from one batch program to another without terminating the parent batch program. The call command accepts the label that is used as the target of the call. If you use Call outside of a script or batch file, it will not work on the command line.

Grammar.

Call [[Drive:] [Path] FileName [BatchParameters]] [: label [arguments]]

Parameters.

[Drive:} [Path] FileName

Specifies the location and name of the batch program to be called. The filename parameter must have a .bat or .cmd extension.

7. Start command

Call external programs, all DOS commands and command-line programs can be called by the start command.

Common parameters of intrusion:

Window minimization at the beginning of MIN

SEPARATE starts a 16-bit Windows program in a separate space

HIGH starts the application in the HIGH priority category

REALTIME starts the application in the REALTIME priority category

WAIT starts the application and waits for it to finish

Parameters these are the parameters passed to the command / program

When the executing application is a 32-bit GUI application, CMD.EXE returns a command prompt without waiting for the application to terminate. If executed within a command script, the new behavior does not occur.

8. Choice command # this command does not know how to use, go online and look for information #

Choice uses this command to allow the user to enter a character to run different commands. The / c: parameter should be added when in use, and the characters that can be prompted for input should be written after c:, with no space between them. Its return code is 1234...

Such as: choice / c:dme defrag,mem,end

Will be displayed

Defrag,mem,end [D,M,E]?

Sample:

The Sample.bat is as follows:

@ echo off

Choice / c:dme defrag,mem,end

This is the end of the article on "how to write BAT scripts". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report