DOS Batch Advanced course Seventh Chapter DOS batch process programming advanced technique _dos/bat

Source: Internet
Author: User
Tags current time ftp commands goto

Interactive interface Design

Nothing to say, look at the Master Design Menu interface bar:

@echo off
CLS
title Ultimate Multipurpose Repair
: Menu
cls
color 0A
echo.
echo         ==============================
echo         Please select the action you want to perform and press Enter
Echo         ======================== = = = = = =
echo.
echo       1. Network repair and Internet related settings, repair ie, custom shielding site
echo.
echo       2 virus kill tool, port Shutdown tool, turn off AutoPlay
Echo.
Echo       3. Clear all redundant startup items, repair system error
echo.
Echo       4. Clean up the system garbage and increase the start speed
echo.
Echo       Q. Exit
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
echo selection is invalid, please re-enter
Echo.
Goto Cho

As long as you have finished the previous chapters of this tutorial, the above procedures should be able to read.

Second, If...else ... Conditional statement

As already mentioned, DOS conditional statements are mainly in the following form
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
Enhanced usage: IF [/i] string1 compare-op string2 command
The enhanced usage plus/I is not case-sensitive!
There are also symbols used to determine numbers in the 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 command command above can use parentheses to combine multiple commands, including the ELSE clause, which can be nested using conditions or looping commands in a combined command.

For example:

IF EXIST filename (
del filename
) ELSE (
echo filename missing
)

Can also be written as:
if exist filename (del filename) Else (echo filename missing)

However, this type of writing does not apply to too many commands or nested commands.

Third, the circular statement

1, the specified number of cycles

FOR/L%variable in (start,step,end) do command [Command-parameters]

Group command:
FOR/L%variable in (start,step,end) do (
Command1
Command2
......
)

2. Execute circular statements on a set.

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 the commands that are executed on each file and use parentheses to combine multiple commands.

FOR/R [[Drive:]path]%variable in (set) do command [Command-parameters]

Check the [drive:]path-rooted directory tree, pointing to the
The For statement. If no directory is specified after/R, the current
Directory. If the set is only one single point (.) character, the directory tree is enumerated.

Like the previous face, the command can be combined with parentheses:
FOR/R [[Drive:]path]%variable in (set) do (
Command1
Command2
......
CommandN
)

3. Condition Cycle

The loop structure above is implemented with the for command, and the for Command loop has the disadvantage that the entire loop is treated as a command statement involving variable latency issues.
Using goto statements and conditions to judge, DOS can implement conditional loop, very simple, see examples:

Cases:

@echo off
set var=0
rem ************ Loop started
: Continue
set/a var+=1
echo%var% secondary cycle
if%var% LSS Goto Continue
rem ************ Loop end
echo loop execution complete
pause

Cases:

@echo off
set var=100
rem ************ Loop started
: Continue
echo%var% cycles
set/a var-=1
if% var% GTR 0 goto continue
rem ************ Loop end
echo loop execution complete
pause

Iv. Sub-Program

In the batch program can call the external running program, such as EXE program, can also call other batch procedures, these can also be considered subroutines, but not convenient, if the program is called a lot, it seems not concise enough, very cumbersome.

In Windows XP, batches can call one of the program segments in this program, which is equivalent to subroutines, which are typically placed behind the main program.

Subroutine call Format:

Call:label arguments

Child program Syntax:
: Label
Command1
Command2
......
CommandN
Goto:eof

In the subroutine segment, parameter%0 refers to the label: label

The sub process is generally at the end, and note that the end of the main program to add exit or jump statements to avoid the wrong entry to the child process.

The variables in both the subroutine and the main program are global variables and are scoped to the entire batch process.

The parameters that are passed to the subroutine are specified in the call statement and are invoked in the subroutine in% 1,% 2 to%9, and the subroutine returns the main program's data simply by referring directly to the end of the call, and, of course, by specifying the return variable, see the example below.

subroutine Example 1:

@echo off
call:sub returns Hello
Echo subroutine return value:%return%
pause

: Sub
set%1=%2
goto:eof

Run Result: Hello

subroutine Example 2: Design a subroutine that asks for the addition of multiple integers

@echo off
set sum=0
call:sub sum
of echo data sum result:%sum%
pause

: Sub
rem parameter 1 is the return variable name
set/a%1=%1+%2
shift/2
if not "%2" = = "Goto Sub
goto:eof

Run Result: 65

In the Win98 system, the above label call is not supported, and the subroutine must be saved separately as a batch program and then invoked.


e-FTP command to achieve automatic download

FTP is a common download tool, the FTP interface has more than 40 commonly used commands, their own learning, not introduced. Here describes how to use the DOS command line to invoke FTP commands, FTP automatic login, and upload the download, and automatically quit the FTP program.

You can actually save the FTP command combination as a text file, and then call it with the following command.

Ftp-n-s:[[drive:]path]filename

The filename above is ftp command file, including login IP address, username, password, operation command, etc.
Cases:

Open 90.52.8.3 # Turn on IP
user iware # User for iware
password8848 # password
bin # binary transfer mode
prompt
CD TMP1 # Switch to Iware user's TMP1 directory
pwd
LCD d:\download # Local directory
mget * Download all files in tmp1 directory bye
# exit FTP


vi. implement command line compression and decompression function with 7-zip

Syntax format: (see 7-zip Help file for details, see dizziness can be skipped, use to learn again)

7z <command> [<switch> ...] <base_archive_name> [<arguments>]

7z.exe each command has a different parameter <switch>, see the Help file
<base_archive_name> for Compressed package name
<arguments> for file name, support wildcard or file list

Where 7z is to the command line compression decompression Program 7z.exe,<command> is the 7z.exe contains the commands listed below:

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. To delete a file from a compressed package
d Command Available parameters:
-I (Include)
-M (method)
-P (Set Password)
-R (Recurse)
-U (Update)
-W (Working Dir)
-X (Exclude)

E:extract extract files to current directory or specified directory
The e command can be used with parameters:
-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 the full paths of the file to the current directory or to the specified directory
X Command parameters available:
-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)

Seven, call VBScript program

With a Windows script host, you can run a script at a command prompt. CScript.exe provides command-line switches for setting script properties.

Usage: CScript script name [scripting Options ...] [Script Parameters ...]

Options:
B Batch mode: Do not display script errors and prompts
D Enable Active debugging
E:engine using 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 Interactive mode (default, relative to//b)
Job:xxxx performs a WSF work
Logo display logo (default)
Nologo does not display logo: Does not display flags when executed
S to save the current command-line options for the user
T:nn Timeout seconds: Maximum time allowed for script to run
X executes the script in the debugger
U indicates redirected I/O from the console in Unicode

Script name is the name of the script file with the extension and required path information, such as D:\admin\vbscripts\chart.vbs.
Script options and parameters are passed to the script. The script parameter has a slash (/) in front of it. Each parameter is optional, but the script option cannot be specified without specifying a script name. If no parameters are specified, CScript displays the CScript syntax and valid host parameters.

Convert Batch to executable:

Because a batch file is a text file, anyone can edit it, accidentally destroy the command inside, so if you convert it to a. com format executable, it will not only improve efficiency, but will not destroy the original function, but also the highest priority. Bat2com can complete this transformation work.

Small knowledge: In a DOS environment, the priority of an executable file is. Com>.exe>.bat>.cmd, that is, if there are four types of files with the same file name in the same directory, when you just type the file name, DOS executes the name.com, and if you need to execute three other files, you must specify the full name of the file, such as Name.bat.

This is a 5.43K size free green tool that can be run on a pure DOS or DOS window command line, usage: bat2com FileName, This creates an executable file named filenme.com in the same directory, and executes the same effect as the original. bat file.

Ix. Time delay

What is a time delay? As the name implies, the execution of an order is delayed for a period of time before the next command.

The application of the delay is shown in the following section: "Simulate progress bar".

1, the use of ping command delay
Cases:

@echo off
echo delay before:%time%
ping/n 3 127.0.0.1 >nul
echo delay:%time%

Explanation: the "/n" parameter of the ping command is used to indicate how many requests to send to the specified IP. In this case, 3 requests to the native IP (127.0.0.1) are sent. 127.0.0.1 can be abbreviated to 127.1. ">nul" is to block out what the ping command shows.

2. Use for command delay
Cases:

Before @echo off
echo delay:%time%
for/l%%i in (1,1,5000) do echo%%i>nul
echo delay:%time%
Pause

Explanation: The principle is very simple, that is, using a cycle of cycles and shielding the content it displays to achieve the purpose of delay.

3, using the VBS delay function, precision millisecond, error 1000 milliseconds

Cases:

@echo off
echo%time% call
:d elay 5000
echo%time%
pause
exit

:d elay
echo wscript.sleep% 1>delay.vbs
CScript//b delay.vbs
del delay.vbs
goto:eof

Run the display:
10:44:06.45
10:44:11.95
Please press any key to continue ...

The above results show that the actual delay of 5500 milliseconds, the extra 500 milliseconds to create and delete temporary files time spent. The error is within a second.

4, only use batch processing command to achieve any time delay, precision 10 milliseconds, error 50 milliseconds

Deferred operations can be implemented with batch commands only.

Cases:

@echo off
set/p delay= Please enter the number of milliseconds to delay:
set totaltime=0
set nowtime=%time%
:: Read start time, time format: 13:01:05.95
Echo Program start time:%nowtime%
:d elay_continue
set/a minute1=1%nowtime:~3,2%-100
:: Minutes from read start time
set/a second1=1%nowtime:~-5,2%%nowtime:~-2%0-100000
:: Converts the number of seconds from the start time to the milliseconds
set nowtime=%time%
set/a minute2=1% nowtime:~3,2%-100
:: The number of minutes to read the current time
set/a second2=1%nowtime:~-5,2%%nowtime:~-2%0-100000
:: Converts the number of seconds in the current time to milliseconds
set/a totaltime+= (%minute2%-%minute1%+60)%%60*60000+%second2%-%second1%
if%totaltime% LSS %delay% goto delay_continue
Echo program end time:%time%
Echo Set delay time:%delay% millisecond
echo Actual latency:%totaltime% millisecond
Pause

Run the display:

Please enter the number of milliseconds to delay: 6000
Program Start time: 15:32:16.37
Program End time: 15:32:22.37
Set delay Time: 6000 ms
Actual delay Time: 6000 ms
Please press any key to continue ...

Implementation principle: First set the number of milliseconds to delay, and then use the cyclic cumulative time 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 theoretically be a 10 millisecond error.
After testing, when the delay time is greater than 500 milliseconds, the above delay procedure generally does not have the error. When the delay time is less than 500 milliseconds, there may be dozens of millisecond error, why? Because the delay program itself has run time, the system time can only be accurate to 10 milliseconds.

For ease of reference, the example above can be changed to a subroutine call:

@echo
off Echo start time:%time% call
:d elay
echo actual delay time:%totaltime% MS
Echo program end time:%time%
Pause
exit

::-----------The following is a delay subroutine--------------------
:d elay
@echo off if "
%1" = "goto:eof
" Set delaytime=%1 set
totaltime=0
set nowtime=%time%
:: Read start time, time format: 13:01:05.95
:d Elay_ 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)%%60*60000+%second2%-%second1%
if%totaltime% LSS%d Elaytime% Goto delay_continue
goto:eof

Ten, the Simulation progress bar

A program to simulate the progress bar is given below. If you use it in 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
for/l%%i in (1 1) do set/p a= /n 1 127.0.0.1>nul
echo  100%%
echo└──────────────────────────────────────┘
Pause

Explanation: "set/p a= <nul" means: "Only show the Message" "and do not wrap, and do not need to enter any information manually, so that each" "on the same line output. "ping/n 0 127.1>nul" is the time interval for each "", that is, the output of a "" every few times.

Xi. input and application of special characters

Start-> run-> enter cmd-> edit-> ctrl+p (meaning allow special characters to be entered)-> Press CTRL + A to display the smiley face pattern.

(If you want to continue typing special characters, press Ctrl+p again, then CTRL + a letter)

The above is a special character input method, selected from the [Hero] tutorial, very useful. That is, use editor edit to enter special characters, then save as a text file, and then open the file under Windows, copy the special symbol.

Some simple special symbols can be entered directly in the DOS command window and saved as text files with redirection.
Cases:

C:>echo ^g>temp.txt
"^g" is input with ctrl+g or alt+007, input multiple ^g can produce multiple beeps.

The application of special characters is also interesting, just one example: Backspace key

The BACKSPACE key indicates the deletion of the left character, which cannot be entered normally in the document, but can be recorded and copied through the edit editing program. That is, "".

With the BACKSPACE key, you can design a blinking text effect

Example: Text flashes

@echo off
: Start
set/p= bed before the bright Moonlight <nul
:: Display text, cursor stops at line end
ping-n 0 127.0.0.1>nul
:: Set delay time set
/ P a=<nul
:: Output Some backspace to place the cursor at the left of the line (the number of backspace can be adjusted by itself).
set/p a=                <nul
:: The output space will overwrite the previously exported text.
set/p A=<nul
:: Again output backspace place the cursor at the leftmost end of the line, the number of backspace here must not be less than the number of spaces above. :
: Otherwise the cursor cannot be returned to the leftmost end.
Goto Start

Example: The output of a Tang poem, flashing many times per line

Copy Code code as follows:

@echo off
Setlocal enabledelayedexpansion

Set str= bed Before the bright Moonlight is the frost on the ground to look at the moon head to think home

:: Define string str for
%%i in (%str%) does (
 REM) assigns each part of STR to the variable%%i, with a space delimiter, because STR contains spaces.
    set char=%%i
    echo.
    Echo.
    FOR/L%%j in (0,1,5) does (
        Set/p=!char:~%%j,1!<nul
 REM takes out each character in the variable char sequentially and displays it.)
        ping-n 0 127.0.0.1>nul
 REM Sets the time delay for outputting each character.
    )
 Call:hero%%i
)
Pause>nul
exit

: Hero
for/l%%k in (1,1,10) do (
 ping/n 0 127.0.0.1> ; nul
 set/p a=<nul
 set/p a=                <nul
 set/p a= <nul
 ping/n 0 127.0.0.1>nul
 set/p a=%1<nul
)
:: Text flashing
goto:eof

12. Application Techniques of random number (%random%)

The%random% system variable returns any decimal digits between 0 and 32767. Generated by Cmd.exe.

2 of the 15 times is equal to 32768, the above 0~32767 is actually the range of 15-bit binary number.

So how do you get a random number within 100? Very simple, the%random% press 100 for the remainder of the operation can be, see examples.

Example: Generate a random number within 5 100

@echo off
setlocal enabledelayedexpansion
for/l%%i at (1 1 5) Do (
  set/a randomnum=!random!%%100
  echo with Number of machines:!randomnum!
)
Pause

Run Result: (different each time running)
Random Number: 91
Random Number: 67
Random Number: 58
Random Number: 26
Random Number: 20
Please press any key to continue ...

The remainder operation set/a randomnum=!random!%%100 100 can be any integer between 1~32768.

Conclusion: Using the system variable%random%, the remainder operation percent, string processing, etc., can achieve a lot of random processing.

Thinking topic: Generating random passwords for a given number of digits

Solution: A string of 26 English letters or 10 digits and other special characters, randomly extracting several characters.

Reference Answer 1: (Simple)

@echo off
Call:randompassword 5 pass1 pass2
echo%pass1%%pass2% 
pause
exit

: Randompassword
::---------Generate random password
::---------%1 is password length,%2, and later for return variable name
::---------The for command can only distinguish between 31 fields
@echo off
set  password_len=%1
if not defined Password_len goto:eof
if%password_len% LSS 1 goto:eof
set Wordset=a b c D E F g h i j k l m n o p q R S t u v w x y z
set return=
set num=0
: RandomPassword1
set/a num+=1
   
    set/a numof=%random%%%26+1
for/f "tokens=%numof% delims="%%i in ("%wordset%") do set return=%return%%%i
if  %num% lss%password_len% goto randomPassword1
if not "%2" = "" Set%2=%return%
shift/2
if not "%2" = "goto Randompassword
goto:eof
   

Reference Answer 2: (Optimal

@echo off
Call:randompassword 6 pass2 pass3
echo%pass1%%pass2% pass1%pass3%
exit

: Randompassword
::---------Generate random password
::---------%1 for password length,%2 and later for return variable name
::---------goto loop, variable nesting, command nesting
@ echo off
If "%1" = "" Goto:eof
if%1 LSS 1 goto:eof
set password_len=%1
set return=
set wordset= Abcdefghijklmnopqrstuvwxyz023456789_
::---------------------------cycle
: RandomPassword1
set/a NUMOF=%RANDOM%%%36 call
set return=%return%%%wordset:~%numof%,1%%
set/a password_len-=1
if% password_len% GTR 0 goto randomPassword1
::---------------------------loop
if not "%2" = "" Set%2=%return%
SHIFT/2
if not "%2" = = "" Goto Randompassword
goto:eof

Note: This example involves variable nesting and command nesting applications, see later.


13. Variable nesting and command nesting

Compared with other programming languages, DOS function is relatively simple, to achieve more complex functions, the need to fully use a variety of techniques, variable nesting and command nesting is one of these techniques.

Let's review the key elements of the previous "string interception":

**********************************************
Intercepting functionality the unified syntax format is:%a:~[m[,n]]%
**********************************************

Square brackets indicate optional,% is variable identifier, a is variable name, not less, the colon is used to separate variable name and description section, symbol ~ can be simply interpreted as "offset" can be, M is offset (the default is 0), n is the Intercept length (default is All).

Percent semicolon if required as a single character, must be written as%

The above is the general format for DOS variable processing, if the M and n are variables, then this is a variable nesting.

For example, to set the variable word "abcdefghij", the variable num is "123456789"
%word:~4,1% is E, where 4 can be taken from the variable num, that is,%num:~3,1%, written in combination form as follows:
%word:~%num:~3,1%,1% after testing this type of writing can not be correctly executed, written%word:~ (%num:~3,1%), 1% also not, then, how to implement this variable nesting? This must be nested with the command.

What is command nesting? Simply put, a single DOS command is used to generate a string, which is another DOS command that invokes the string with the call statement to execute it, resulting in the final result.

Example: Implementing command nesting with the call statement

@echo off
set str1=aaa echo OK BBB
echo initial string:%str1%
echo generates the command string as follows:
echo%str1:~4,7%
Echo Run command string generation The final result is: Call
%str1:~4,7%
Pause

Run the display:
Initial string: AAA echo OK BBB
The command string is generated as follows:
Echo OK
Run command string generation The final result is:
Ok
Please press any key to continue ...

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.