BAT 脚本常用命令
注释
@REM 这是注释
不显示后续命令
@echo off
暂停等待按键
@echo off
:begin
copy a:*.* d:\back
echo Please put a new disk into driver A
pause
goto begin
pause 命令会使程序挂起,按任意键继续。
获取执行命令时附加的参数
%0 代表命令本身,%1 代表第一个参数,依此类推。
显示文件内容
type ssssmy.txt
调用其他 bat 文件
call ssssmy.bat
从一个批处理程序调用另一个,不终止父批处理程序。
call [[Drive:][Path] FileName [BatchParameters]] [:label [arguments]]
filename 必须有 .bat 或 .cmd 扩展名。
调用外部程序(start)
所有 DOS 命令和命令行程序都可由 start 调用,常用参数:
MIN开始时窗口最小化SEPARATE在分开的空间内开始 16 位 Windows 程序HIGH在 HIGH 优先级类别开始应用程序REALTIME在 REALTIME 优先级类别开始应用程序WAIT启动应用程序并等候它结束
if 语句
if [not] “参数” == “字符串”
if "%1"=="hello" call ssssmy.bat
if [not] exist [路径]文件名
if exist c:\1.bat type c:\1.bat
if errorlevel <数字>
if errorlevel 2 goto x2
返回值必须按从大到小排列。
goto
goto end
:end
echo this is the end
通常与 if 配合,根据不同条件执行不同的命令组。
choice 选择菜单
choice [/C choices] [/N] [/CS] [/T timeout /D choice] [/M text]
| 参数 | 说明 |
|---|---|
/C choices |
选项列表(默认 YN) |
/N |
隐藏选项列表 |
/CS |
区分大小写 |
/T timeout |
超时秒数(0-9999) |
/D choice |
超时后的默认选项 |
/M text |
提示文本 |
示例:
@echo off
choice /C dme /M "defrag,mem,end"
if errorlevel 3 goto end
if errorlevel 2 goto mem
if errorlevel 1 goto defrag
:defrag
c:
goto end
:mem
mem
goto end
:end
echo good bye
for 循环
:: 对一组文件执行命令
for %%c in (*.bat *.txt) do type %%c
:: /f 模式:解析命令输出
for /f "skip=2 delims=\r\n tokens=*" %%a in ('netsh lan show interface') do echo "%%~a"
语法:
FOR %%variable IN (set) DO command [command-parameters]
获取网络适配器
@REM 获取网络适配器
netsh lan show interfaces|more
如果显示「有线自动配置服务(dot3svc)没有运行」,输入 net start dot3svc 开启即可。
路径变量
%cd%— 当前工作路径%~dp0— bat 文件所在路径
原文链接:https://www.ssssmy.com/notes/bat-jiao-ben-chang-yong-ming-ling