Super-detailed explanation of bat script common commands and pro-test sample code

This article mainly introduces the common commands of the bat script and the super-detailed explanation of the sample code of the personal test. Here you need to pay attention to editing the bat file, please use ANSI encoding, otherwise Chinese garbled characters are easy to appear. Friends who need it can refer to the following

1. Statement comment

rem command line comment, which can be echoed (the statement will be displayed on the command line);

:: two colons, the effect is the same as above, but will not be echoed. (Any non-alphanumeric character after the colon can be used as a comment)

2. Pause

pause , "Please press any key to continue..." appears in the command line

Customize the text when paused, as follows:

::pause>nul,隐藏原暂停文本
echo 这里是自定义文本! & pause > nul

3. Output and newline

Add content after echo to output the content, such as: echo "welcome!";

echo . Newline command, that is, add a point after echo

4. Turn on and off the echo

If @ is placed before the statement, the statement will not be echoed (ignore echo on)

echo off turns off the echo function until echo on appears, but it will echo itself, so it is often used with @ before, that is, @echo off (turn off all echo functions)

5. Create a new file and add file content

@echo off
rem 格式:echo 文件内容>文件路径
echo @echo off>test1.bat
::其中>>在文末添加,>覆盖原内容
echo echo this is test>>test1.bat
echo pause>>test1.bat
rem 显示该文件内容
type test1.bat
pause

insert image description here

6. Set the title title

@echo off
::title设置标题
title 我测试一下!
pause

insert image description here

7. Set the color

Example: color 0A
insert image description here

8. If statement judgment

Special attention: the if statement block is loaded as a statement when it is executed, so it is necessary to solve the problem of its internal variable reference through the delayed assignment in 11

::if常规用法,注意空格
@echo off
:start
set /p a=
if not %a%==1 (
	echo 请输入1
	goto start
) else (
	echo 输入正确
)
pause>nul

@echo off
if not exist d:\test.bat (
	echo @echo off>d:\test.bat
) else (
	del d:\test.bat
)
pause>nul
@echo off
set a=1
if defined a (
	echo 已定义a
) else (
	echo 未定义a
)
pause>nul
@echo off
set a=123
set b=abc
set c=12
::/i字符串大小写忽略
if /i %b% equ ABC (
  if %a% geq %c% (
    echo %a%^>=%c%
  ) else (
    echo %a%^<%c%
  )
) else (
  echo %b%不等于ABC
)
pause>nul

The above operands can be strings, numbers, and variables; when the strings involved in the comparison are strings, they will be converted to ASCII codes for comparison; the comparison operators are as follows: 'and', ' in the if
insert image description here
statement Or', 'not' logic judgment

::'与'一般用if嵌套实现
@echo off
set /p a=
::当a小于10且大于0
if %a% lss 10 if %a% gtr 0 echo 输入的是0-10
pause
::'非'not可以实现
@echo off
set /p a=
::a不小于10
if not %a% lss 10 ( echo 输入的是不小于10 )
pause
::'或'实现一:使用if嵌套(代码简洁但逻辑不太好理解)
@echo off
set /p a=请输入a:
set /p b=请输入b:
::a小于5或b小于5if %a% lss 5 (echo a小于5或b小于5) else (if %b% lss 5 (echo a小于5或b小于5) else (echo a、b都不小于5))
pause
::'或'实现二:使用额外变量标记结果,再判断该变量(逻辑简单但代码多)
@echo off
set /p a=请输入a:
set /p b=请输入b:
::a小于5或b小于5时
set flag=0
if %a% lss 5 set flag=1
if %b% lss 5 set flag=1
if %flag% equ 1 ( echo a小于5或b小于5 ) else ( echo a、b都不小于5 )
pause

9, goto statement jump

@echo off
::使用冒号加标记名作为goto语句的标记
:start
set /p param=
if %param%==4 (echo 请不要输入4& goto start) else (echo %param%)
pause

10. Set usage to receive user input data

@echo off
set /p param=请输入密码:
echo %param%
pause

insert image description here

11. Definition of variables and delayed assignment of set usage

Please pay special attention to this mechanism, it is really disgusting

::输出为1
@echo off
set a=1
set a=2&echo %a%
pause

Note: Before the batch process runs "set a=2&echo %a%", it will first read and preprocess the entire sentence, that is, assign a value to the variable a, then the value of %a% is 1, to solve the problem For this problem, batch processing is designed with variable delays. That is to say, after reading a complete statement, the variables in the line are not assigned immediately, but are assigned before a single statement is executed. The specific implementation is as follows:

::输出为2
@echo off&setlocal enabledelayedexpansion
set a=1
set a=2&echo !a!
pause

Note: there should be no spaces between 'variable name=value'

@echo off
::0赋值给b
set b=0
echo b:%b%
::将空格和0赋值给a
set a= 0
echo a:%a%
::无法赋值
set c =0
echo c:%c%
pause

insert image description here

12. System variables for set usage

@echo off
::查看所有环境变量
echo ----------------ALL----------------------
set
echo ----------------END----------------------
::查看环境变量JAVA_HOME的值
if defined JAVA_HOME ( echo JAVA_HOME:%JAVA_HOME% ) else ( echo 未定义JAVA_HOME )
pause

13. Definition of set usage##Definition of digital expressions

@echo off
set a=1&set b=6
set c=%a%+%b%
::输出1+6
echo %c%
set d=a+b
::输出a+b
echo %d%
set /a e=a+b
::输出7
echo %e%
pause

14. For statement loop

@echo off
::关键字for、in、do必有,括号必有
::分隔符可以是逗号、分号、等号、空格
::输出为A换行1换行B。。。
for %%i in (A,B,C) do echo %%i & echo 1
pause>nul
@echo off
::找出D盘下所有文件
for %%i in (d:\*.*) do echo "%%i"
pause
@echo off
set str=c d e f g h i j k l m n o p q r s t u v w x y z
echo 当前硬盘的分区有:
for %%i in (%str%) do if exist %%i: echo %%i:
pause
@echo off
::找出当前目录下文件名为四个字符的txt文件
for %%i in (????.txt) do echo "%%i"
pause

15. Variable %0–%9

%0 refers to the file itself, %1–%9 are the received parameters, %1 of the subroutine in the following example is the param1 transmitted by the main program, %2 is the param2

::该文件名为test.bat
@echo off
echo 这是主程序第一个输出
timeout 2
start test1.bat param1 param2
timeout 2
echo 这是主程序第二个输出
pause
::该文件名为test1.bat
@echo off
timeout 2
echo 这是子程序第一个输出
echo 这是接收到的第一个参数%1 和第二个参数%2
pause
@echo off
set /p param=
if %param%==4 (echo 请不要输入4) else (echo %param%)
::%0在当前窗口重新调用自身
%0

16. Switch directory

::@echo off
::显示当前目录
cd
::切换到根目录
cd\
::盘符加冒号,切换到该盘
d:
::切换到e:hi目录下(目录名不区分大小写)
cd /d e:\hi
::保存当前目录,并切换当前目录为d:\test
pushd d:\test
::恢复当前目录为刚才保存的e:\hi
popd
pause

insert image description here

17. The md command creates a folder

::创建文件夹
md e:\test\test1
::文件夹名有空格需要加引号
md "e:\test op"
::空格隔开,创建多个
md e:\test1 e:\test9\test2 "e:\test5 lmn"

18. The rd command deletes a folder

@echo off
::删除e:\test op下空文件夹,不为空不能删除
rd "e:\test op"
::删除e:\test9下所有文件夹,不管是否为空,但会询问是否确认删除[Y/N]
rd /s e:\test9
::自定义删除提示信息
echo 是否删除[Y/N]: & rd /s e:\test9>nul
::/s/q联合使用,不会询问直接删除
rd /s/q e:\test9

19. The move command moves files (folders)

@echo off
::文件夹移动,如果test文件夹存在,则将test5文件夹移动到test文件夹下
::如果test文件夹不存在,则将test5文件夹移动到test1文件夹下并重命名为test
::注意:文件夹移动不能跨分区
move e:\test5 e:\test1\test
::将d:\test\1.txt文件移动到e:\下并重命名为23.txt
::如果该目录已存在23.txt,则会覆盖
move d:\test\1.txt e:\23.txt>nul&&echo 移动成功并重命名
::将e:\23.txt文件移动到e:\test文件夹下
move e:\23.txt e:\test>nul&&echo 移动到文件夹下

20. The del command deletes files

@echo off
::删除该层目录下的所有文件,需要确认[Y/N]
del d:\test
pause
::不需要确认
del /q d:\test
::删除该目录下所有层级的文件,不删除文件夹,需要逐个文件夹确认
del /s d:\test
::删除文件111.png,不需要确认
del d:\test\111.png

21. Cope command to copy files

@echo off
::将d:\test\test.txt复制到e:\test1\目录下并重命名为test2.txt
::如果test2.txt文件已存在,将自动覆盖
copy d:\test\test.txt e:\test1\test2.txt
::将e:\test该层目录下所有文件复制到d:\test1\test3文件夹下
::前提d:\test1\test3文件夹必须已存在
::相同文件名的文件会被覆盖
copy e:\test d:\test1\test3

22. xcope command to copy files

@echo off
::将e:\test目录下所有文件()复制到d:\test1
::/e目录下所有文件(),/y已存在时直接覆盖
xcopy e:\test d:\test1 /e/y

23. The cope command merges files

@echo off
cd /d d:\test
::129.txt和156.txt两个文件内容合并存入新建的new.txt中
copy 129.txt+156.txt new.txt
::打印出new.txt中的内容
type new.txt
::将d:\mp3\111.mp3和e:\2.mp3以二进制数据合并复制到d:\new.mp3
::其中/b二进制,/a文本形式
copy /b d:\mp3\111.mp3+e:\2.mp3 d:\new.mp3

24. The ren command renames files (folders)

@echo off
::1.txt重命名为58.bat
ren d:\test\1.txt 58.bat
::将d:\test\目录下所有文件名为1开头的txt文件改为bat文件
ren d:\test\1*.txt *.bat
::将d:\test\目录下所有文件名为1开头三个字符的bat改为txt文件
ren d:\test\1??.bat ???.txt

25. Call use

Call the subscript in the program, run the subscript code in the current program, and continue to execute the code after the subscript after the subscript is executed

::该文件名为test.bat
@echo off
echo 这是主程序第一个输出
timeout 2
call test1.bat param1 param2
timeout 2
echo 这是主程序第二个输出
pause
::该文件名为test1.bat
@echo off
timeout 1
echo 这是子程序第一个输出
echo 这是接收到的第一个参数%1 和第二个参数%2
pause

insert image description here

26, timeout delay

@echo off
set a=1
:start
echo %a%&set /a a=a+1
timeout 1 > nul
goto start
pause
@echo off
::每隔一秒输出斐波拉契数列
set a=1
set b=1
echo %a%&timeout 1 >nul
echo %b%&timeout 1 >nul
:start
set /a c=a+b
echo %c%&set a=%b%&set b=%c%
timeout 1 > nul
goto start
pause

27, start life

Note : When executing start, a new thread will be opened to execute the program, and the original program will continue to execute without being affected

@echo off
::打开test.txt文件
start e:\test.txt
::启动jar包
start java -jar e:\demo.jar
pause

Start a new cmd window and execute the command inside it

https://www.jb51.net/article/245248.htm

28. Call the bullet box

::一、MSG命令方式
@echo off
::/time:5设置时间弹框的显示时间为5S,5S后自动关闭
msg * /time:5 这里是弹窗显示的文本
pause
::设置弹窗的多行文本
(echo 这是弹窗的第一行文本
echo 这是第二行文本)|msg * /time:5
pause
::一、调用VBScript的MsgBox实现弹窗
@echo off
::第二个参数65的解释在代码之后的列表中
mshta vbscript:msgbox("弹窗单行显示内容",65,"弹窗的标题")(window.close)
::多行显示文本可在文本中使用vbCrLf或vbNewLine
set msg="多行显示vbCrLf这是第二行vbNewLine这是第三行"
mshta vbscript:msgbox(Replace(Replace(%msg%,"vbCrLf",vbCrLf),"vbNewLine",vbNewLine),6,"自定义标题")(window.close)

The value of the button parameter of MsgBox is as follows:

0 = vbOKOnly - Show only OK button.
1 = vbOKCancel - Show OK and Cancel buttons.
2 = vbAbortRetryIgnore - Displays the Abort, Retry and Ignore buttons.
3 = vbYesNoCancel - Displays Yes, No, and Cancel buttons.
4 = vbYesNo - Displays yes and no buttons.
5 = vbRetryCancel - Show retry and cancel buttons.
16 = vbCritical - Display critical information icon.
32 = vbQuestion - Show warning query icon.
48 = vbExclamation - Show warning message icon.
64 = vbInformation - Displays the information message icon.
0 = vbDefaultButton1 - The first button is the default button.
256 = vbDefaultButton2 - The second button is the default button.
512 = vbDefaultButton3 - The third button is the default button.
768 = vbDefaultButton4 - The fourth button is the default button.
0 = vbApplicationModal - application modal: the user must respond to the message box to continue working in the current application.
4096 = vbSystemModal - System Modal: All applications are suspended until the user responds to the message box.
Note: The first set of values ​​(0 - 5) is used to describe the type and number of buttons displayed in the dialog; the second set of values ​​(16, 32, 48, 64) is used to describe the style of the icon; the third set of values ​​(0 , 256, 512) determine the default button; the fourth set of values ​​(0, 4096) determines the style of the message box. When adding these numbers to generate the buttons parameter value, only one number can be taken from each set of values.

29. Obtain administrator privileges

You can try the following two ways

@ echo off
%1 %2
ver|find "5.">nul&&goto :Admin
mshta vbscript:createobject("shell.application").shellexecute("%~s0","goto :Admin","","runas",1)(window.close)&goto :eof
:Admin
::上面这段代码之后执行的所有东西都是管理员权限方式
@echo off
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' NEQ '0' (
	echo 请求管理员权限...
	goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
exit /B
:gotAdmin
echo 获得管理员权限
pause

30. The for statement reads the contents of the file

@echo off
::按行读取d:\test.txt文件中的内容,输出每行的第一个数据,默认每行内以空格和tab为分隔符
for /f %%i in (d:\test.txt) do echo %%i
::delims参数指定分隔符为/
for /f "delims=/" %%i in (d:\test.txt) do echo %%i
::tokens参数指定读取第二列,tokens=*读取所有
for /f "tokens=2 delims=/" %%i in (d:\test.txt) do echo %%i
::skip参数直接跳过前两行,从第三行开始
::tokens=2,*读取第二个和之后剩余所有,%%i为第一列值,%%j为之后剩余所有
::tokens=1,4读取第一个和第四个,%%i为第一列值,%%j为第四列值
::('net start')表示将单引号内语句的执行结果作为集合
for /f "skip=2 tokens=1,* delims=/" %%i in ('net start') do echo %%i %%j
::("asc/2ap/as5")表示对字符串进行处理
for /f "tokens=2,* delims=/" %%i in ("asc/2ap/as5") do echo %%i--%%j
::eol参数直接忽略以#开头的行
for /f "eol=# tokens=*" %%i in (d:\test.txt) do echo %%i

31. sc and net commands

@echo off
::关闭/启动MySQL服务,执行该条语句后会立即执行之后的代码,不会等待停止/启动的过程
sc stop MySQL
sc start MySQL
::设置MySQL服务为自启动,demand手动,disabled禁用
sc config MySQL start= auto
::安装服务
sc create MySQL binPath= "F:\installFiles\mysql-5.7.1.exe"
::卸载服务(卸载前先关闭服务)
sc delete MySQL
::关闭/启动MySQL服务,等待停止/启动的过程,完成后执行之后的代码
net start MySQL
net stop MySQL
::查看所有运行的服务
net start

32. ping command

@echo off
ping 192.168.0.225
::无休止ping某地址
ping www.baidu.com -t

33. mshta command

::可以调用vb脚本和js脚本
mshta vbscript:window.execScript("alert('hello world!');","javascript")(window.close)
mshta javascript:window.execScript("msgBox('hello world!')(window.close)","vbs")
mshta vbscript:msgbox("弹窗单行显示内容",65,"弹窗的标题")(window.close)
mshta vbscript:CreateObject("Wscript.Shell").popup("弹窗内容",7,"标题",64)(window.close)
::连续弹二个信息框
mshta vbscript:execute("msgbox ""one BOX"":msgbox ""two BOX"":window.close")

34. exit to exit the script and check the return code errorlevel

@echo off
set a=1
set b=
if defined a if defined b echo 都搞定了,按任意键就可以撤了!&pause>nul &exit
echo 我去!还有没赋值的?
pause
@echo off
::格式化A盘---请谨慎操作,一般莫搞骚操作
format a:
::用以判断上一条命令是否执行成功,默认为0,出错为1
echo %errorlevel%
::这个很好理解 就是判断errorlevel为0
if %errorlevel% == 0 echo 搞定
::下面相当于判断errorlevel大于等于0 等同于%errorlevel% GEQ 0 
if errorlevel 0 echo 搞定
::下面相当于判断errorlevel大于等于0且小于1 等同于%errorlevel% == 0
if errorlevel 0 if not errorlevel 1 echo 0
pause

When the subroutine exits, exit /b num can be used to specify the return code, and the main program can receive the return code with errorlevel

@echo off
echo this is test.bat
echo %errorlevel%
call test1.bat
echo %errorlevel%
pause
@echo off
echo this is test1.bat
echo 按任意键结束test1.bat!&pause>nul &exit /b 123

insert image description here

  • Please use ANSI encoding for scripts
  • Many operations require administrator privileges, so be careful to execute scripts with administrator privileges
  • The one-time loading of the if statement is really disgusting, variable assignment pay attention to lazy loading
  • Avoid special character parentheses in strings
  • After the environment variable is set, it can be viewed in a new window, so it cannot be viewed immediately after the setting is completed. The %0 call itself continues to execute in the current window, and cannot be viewed

This is the end of this article about bat script common commands and pro-test sample codes explained in detail

I hope it can be of some help to you who need to view this information!

Guess you like

Origin blog.csdn.net/weixin_45127646/article/details/128416058