   『楼 主』:
自断断续续学习的笔记
使用 LLM 解释/回答一下
2007-12-03
有WINDOWS为何还学DOS?
因为DOS在某些方面效率更高;学习Linux 交换机/路由器DOS更方便;远程控制。
一、入门与概述
1.文件与目录
文件名:文件基本名+后缀
文件基本名:1-8个字符,对于文件名必须存在;后缀0-3个字符,可有可无。
目录:在Windows中称作“文件夹”。
用DIR显示时,后面跟有[dir]标志,表明它们是目录。
2.exe:可执行文件
com:命令文件
bat:批处理文件
它们都被称作“可执行文件”。
Bat后缀的文件优先级高于以exe和com为后缀的文件
3.DOS内部命令和外部命令
内部命令是由command.com随系统启动直接加载到内存中去的,可直接使用。
换句话说,内部命令存在于command.com文件中。
外部命令是一个个独立的文件,存在于磁盘中,需要时可调入内存执行。
4..和..与\
. :当前目录
.. :当前目录的上一级目录,也称“父目录”
\ :根目录。
5.Dir命令
当前目录存在.和..时,用dir命令显示当前目录信息时,它们被认为是一个文件,只是大小为零。
6、DOS启动顺序
启动——》IO.SYS——》MSDOS.SYS——》CONFIG.SYS——》COMMAND.COM——》Autoexec.bat
其中,IO.SYS、MSDOS.SYS、COMMAND.COM对于DOS系统的启动必不可少。
io.sys : 输入输出处理程序
Msdos.sys :文件处理程序
Command.com :命令处理程序
新解:
对于DOS,硬盘启动时首先有INT19中断来读取“硬盘MBR”,读到后将MBR读到内存0000:007c,接着INT19也跳到内存中0000:007c,此时的控制权还是INT19,接着在MBR中“有一个程序”会寻找“可引导的分区”,找到后将引导分区读到0000:007c,这时MBR程序就会跳到0000:007c这个地址上,系统开始启动了。
主引导扇区是:0柱0磁头1扇区
之后就是FAT(文件分配表)了
补充(2007-12-10)
。DOS :disk operating system,单用户单任务OS。
冷启动 :开机时,打开显示器电源-》主机电源,关机时顺序相反
热启动 :系统启动时,按CTRL+ALT+DEL组合键再次启动系统
二者区别 :是否跳过内存检测等一些硬件检测过程,其它运行过程相同
。DOS常用保留名
CON :键盘\显示器
NUL :空设备或虚拟设备
AUX/COM1 :第一串行通信接口
COM2\COM3\COM4 :第2、3、4串行口
LPT1\PRN :第一并行接口
。批处理文件可以理解成“一个DOS命令”
。为何不要将批处理文件命名为DOS的“内部命令或外部命令”?
答:如果与内部命令同名,则DOS内部命令优先级高于批处理,批处理文件不能执行;
如果与外部命令同名,则取决于“先找到外部命令还是先找到批处理文件”,谁先被找到
就先执行,因此,建议命名批处理时要避免与DOS的内、外部命令同名。
。DOS下创建批处理文件的方式?
a copy con 要创建的批处理文件
b edit 要创建的批处理文件
。也可以用
Pause 要显示的信息 有类似与 echo 要显示的信息
。如何让“批处理文件”鸣镝?(依靠计算机内置扬声器)
在DOS下用edit 鸣镝.bat,之后进入编辑页面,先输入
Pause在输入一个空格,之后在按住CTRL键,按“P”键,松开CTRL键,再按住CTRL键,在按“G”,即可生成一个“鸣镝控制符”。
也可以按住CTRL键不松手,先后按“P”和“G”键。
其实,用echo也能达到同样效果,只是在文本中输入控制符麻烦,可在DOS下编辑批处理文件,输入控制符并保存后在返回到Windows下编辑,不失为一个好办法。
。
二、DOS命令简介
1.Dir
显示当前目录信息,但不包括系统和隐藏文件
dir /p :分屏显示信息(p是page的缩写,即分页显示屏幕)
dir/w :用宽列表显示信息,没有文件大小和创建日期
dir/d :类似于dir/w显示方式
dir/b :只显示文件名,目录名也按照文件名方式显示,不显示目录名的[ ]标志(一种精简显示)
dir /l :以小写字母显示文件和目录
dir /a: :显示指定属性的文件,例:dir /a:r显示当前目录下的所有具有只读属性的文件
例:dir /a:d表示只显示目录信息
例:查找指定日期的文件 dir|find “2007-12-04”,注意日期的书写格式和本机日期显示匹配
例:在多级目录下查找文件,使用参数/s,如 dir temp /s,如果当前目录下有temp目录,temp下还有temp目录,则执行结果是列出最后一层temp目录下的所有文件
REM
dir/?看帮助,发现a后的:是可选的,但如果不用:,则会显示“当前的驱动器的卷没有标签,找不到文件”信息。
不用:,怎么又好使了?自己疏忽吧!
Dir /a:-r :显示当前目录下所有具有非只读属性的文件
- :表示“否的前缀”。
REM
Dir /o: 按照分类方式显示信息,如文件大小、字母顺序等,例:dir /o:s表示按照文件大小显示信息;dir /o:n按照字母顺序显示信息
Dir /n :以“长文件列表方式显示,文件名在最右侧”
Dir /c :类似于dir/n
Dir/x :显示非8dot3命名规则的文件
例:dir >test.txt 表示将dir命令结果导入到一个文本文件里
2.Cd
Change directory改变目录
注意:如果在C盘使用如下命令
c:\>cd e:\test
结果仍在c:\>在,只不过在转到d盘,d盘的当前目录是d:\>test>,我在用at定期删除某目录下的文件就出了以上问题。
例:
@echo off
c:
rem 当时我望了转到c:,结果删除了批处理文件所在的磁盘很多文件,包括批处理文件本身
rem 使得at任务无法执行
cd "C:\Documents and Settings\All Users\Application Data\Symantec\Symantec AntiVirus Corporate Edition\7.5\Logs"
echo y | del *.*
Cd .. 表示回到上一级目录
Cd\ 表示回到根目录
Cd /d 参数/d表示即改变当前目录,也改变当前驱动器
3.Copy
功能是复制与移动,但不能复制目录中的子目录
例:合并两个文本文件1.txt和2.txt为3 .txt
Copy /a 1.txt+2.txt 3.txt
REM 按照ASCII码合并这两个文件
Copy /b 1.txt+2.txt 3.txt
REM 按照二进制合并这两个文件
参数/a和/b不能一起使用,其中/a只能合并纯文本文件,而/b即能以文本方式合并,又能以二进制方式合并
例:加密文件
copy /b test.jpg+1.txt 2.jpg
REM test.jpg和1.txt变成一个文件2.jpg,这样文本信息得到了加密,需要查看该信息,可使用ultraedit软件查看
REM 记住,要加密的文档一定要放到+号右侧
4.Xcopy
可以将目录中的非空子目录复制到其它地方,但要使用参数/s
/e必须与参数/s同用,表示不仅可以拷贝子目录,空目录也可以拷贝
/v拷贝后许进行校验
5.Del
Delete
Del *.* 非常危险的命令
例:del /f 强制删除只读文件 Del/a 删除指定属性文件
6.ren
Rename
7.type
一次只能显示一个文件的内容
8.Format与unformat
格式华后的磁盘可利用空间等于磁盘总空间,说明磁盘性能不错
Format /u 表示无条件格式化,此时unformat无效
例:Echo y|formant a:
Unformat 盘符 表示恢复已格式化的磁盘
unformat /l 表示列出可恢复的文件列表
9.Md与Rd
新建目录
例:同时建立多个目录
md c:\1 d:\2 e:\3 等价于md c:\1;d:\2
删除目录,所删除的目录里不能有子目录和文件,如果想这样执行,可使用
Rd /s
例:建立一个加密目录及如何查看和删除它
md test..\
这样就建立了一个“加密”的文件夹,双击无法打开它
可通过“开始”菜单中的“运行”或“资源管理器中的地址栏”输入它的“完整路径”查看
通过 rd /s /q删除它
思考:如果建立的“加密”文件夹和属性隐藏的方法包括注册表隐藏结合起来,就可以建立一个相对私秘的空间。
注册表大概位置:MACHINE\SOFTWARE\WINDOWNS\CURRENTVERSION\EXPLORER\ACVANCED\FOLEDR\SHWOALL\CHECKEDVALUE的值
10.Deltree
删除目录树,非空目录照删不误
Deltree *.*非常危险的命令
11.Mem
Memory
12.Chkdsk
Checkdisk
13.Sys
C:\>sys a:等同于format a:/s,都是制作系统启动盘
如果copy一张DOS启动盘,io.sys和msdos.sys这两个文件不一定能拷贝到磁盘最前面的磁道上
14.Cls
清屏
15.More
分屏显示
16.Move
例:@echo off
Cd c:\test
Move c:*.* a:
REM
注意第3行“c:与*.*”之间没有“\”,这表示将当前目录即test目录下的所有文件拷贝 到A盘。
17.Help
人如其名
18.Attrib
Attribute
例:将c:\test目录下的所有文件和子目录(包括目录本身)都设置为“只读”属性
Attrib +r c:\test /s /d
/s :表示对子目录进行操作
/d :表示对目录进行操作,可简单理解为directory
例:将c:\test目录下的所有文件和子目录(不包括目录本身)都设置为“只读”属性
Attrib +r c:\test\*.* /s /d
19.Time与date
Date /t :不需输入新时间
Echo+|date|find “当前日期”
Echo+|time|find “当前时间”
例:可编写一批处理文件记录机器时间使用的状况
echo+|date/t>test.txt
Echo+|time/t>>test.txt
20.Lable
21.Defrag
整理磁盘碎片
22.Doskey
建立和调用DOS宏命令
例:doskey d=deltree,以后执行d就相当于执行deltree命令
例:如果在CMD下输入了很多的命令,需要再次使用这些命令而又不想重复输入时,可使用doskey,具体操作(在CMD):doskey /h(h是history)是查看曾经在CMD下已经使用的命令,可通过F9键调出它们的缓存表再次使用,也可以使用上下箭头或PaUp和PaDn键来操作,如果想清除他们,可使用doskey /reinstall。
23.Fdisk
Fdisk /mbr :重新建立DOS主引导记录
24.Memmaker
内存优化命令
25.Emm386
扩展内存管理
26.Lh 或loadhigh
将程序载入高端内存
27.Msd
系统检测
不能直接使用
28.Undelete
该命令使用前,需要使用lock命令,解除对硬盘目录区不让修改的限制
Undelete /all :恢复所有del的文件,不用询问
Undelete /list :列出可恢复的文件列表
29.Path
例:path c:\test
如果在当前目录下执行某命令,不存在,则在path设置的路径下继续寻找该命令,有则执行
30.Prompt
设置提示符,就是我们常见的c:\>,c:表示当前盘符是C盘,\表示根目录,>表示将提示符与待输入的命令分开
可以根据需要将c:\>改变
31.Backup与restore
备份与恢复
Restort /s :包括子目录恢复到指定的目录中
32.Edit
只能编辑文本文件,编辑的文件存在则编辑,不存在则临时建立该文本文件并进入编辑状态,如果保存就会在磁盘上建立该文件
33.Set
设置变量,在CMD下直接输入set命令,会列出绝大部分的系统变量
例:set path=c:\test 等同于path c:\test
例:手动输入变量值
set /p a= 请输入你的选择
REM 在纯DOS环境下,/p参数不存在,该语句自然不好使!
REM 可通过setx命令自行定义类似系统变量的变量(重新启动机器后仍然存在的那种变量),但XP系统中没有该命令,2003中有。格式:setx 变量 赋值
Set /a var=
REM 对变量进行算术运算
例:set /a var+=1
Set %path:str1=str2%
REM 用str2替换str1
例:@echo off
set var= zgk.com
Echo 显示var原值
echo %var%
pause
set a=%var: =%
Rem 原变量中的空格被替换掉
echo 显示替换后的var值
echo %a%
set b=%var:.=%
echo %b%
rem 原变量中的点“.”被替换掉
pause
set %path:~10,5%
REM 截取指定变量的列数
例:@echo off
Set var=zgk.com
Echo %var%
Set b=%var:~2,3%
Rem 截取指定变量var的前2列,也就是说要从第3列开始读取3个字符赋给新的变量b,rem 那么b=k.o
Echo %b%
Pause
Set %path:~-10%
例:@echo off
set var=zgk.com
Echo %var%
Set b=%var:~-3%
Rem 从后往前取指定变量var的3列赋给新的变量b,那么b=com
Echo %b%
Set c=%var:~3%
Rem 从头开始截取指定变量var的前3列,就是说将var的第4列后的所有变量赋给c,rem 那么c=.com
Echo %c%
pause
Set %path:~0,-2%
例:@echo off
set var=zgk.com
Echo %var%
Set b=%var:~-3%
Rem 从后往前取指定变量var的3列赋给新的变量b,那么b=com
Echo %b%
Set c=%var:~0,-2%
Rem 从后去掉var的2列,之后从将var赋给c,那么c=zgk.c
Echo %c%
pause
34.Smartdrv
设置磁盘高速缓存
35.Append
设置非可执行文件路径
例:当前目录里没有test.txt,c:\下有
append c:\ 类似于path命令
36.Debug
Debug 文件名
37.Diskcomp
比较两张软盘内容
38.Expand
解压命令
Expand 原压缩文件路径 目的地
39.Fc
比较两个文件内容
例:fc /c test1.txt test2.txt
Rem /c 不分大小写比较
40.Fasthelp
快速帮助
XP系统下没有
Fashhelp command 等价于 command/?
41.Qbasic
启动basic集成环境
42.Setver
设置版本,还能查看到winword和excel的版本
在config.sys中常用语法:device=setver.exe
REM
没在config.sys中加入device=setver时,还能看到winword和excel的版本,加上了它怎么就什么也看不到呢?也没有错误提示信息
REM
43.Share
44.Subst
用指定的路径替代某个盘符
例:subst a: c:\test 表示用C盘下的test目录替代A盘
Subst a: /d 表示删除替代
45.Tree
显示当前目录或指定目录下的所有子目录结构,但并不显示文件名
/f (file) :显示目录的同时还显示目录下的文件名
Tree /a :以ascii码显示目录树
例:查找c:\test目录下的test.txt的个数
tree /f c:\test | find /c /I “test.txt”
如果文件太多超出缓冲区大小,可使用:tree /f |more
46.Vsafe
病毒防护程序,没试过!!!!!!!
47.Ver
查看DOS版本号
48.Vol
查看磁盘的卷标号
49.Ctty
改变控制的输入输出设备
例:ctty aux 表示设置aux为输入输出设备
50.Recover
覆盖磁盘
51.Replace
例:replace c:\test1.txt d:\test2.txt /r
即使test2.txt具有只读属性,也将被替换
例:replace d:\a.txt d:\backup /s /p /u
/s :用D:\a.txt替换D:\backup及其子目录下所有的同名文件
/p :替换前要进行确认
/u :(update),在替换前检查源文件与被替换的目标文件的修改时间,如果前者更新,则不进行替换
例:@echo off
cd %1
for %%i in (*.%3) do if not exist "%2%%i" copy %%i "%2" /y
replace *.%3 "%2" /u
执行filesyn.bat d:\ e:\ txt
52.at
定制计划任务(该命令定制的计划任务是后台运行的,而在Windows下“任务计划”定制的任务是前台运行),二者的主要区别还有at命令只能查看有at命令本身定制的计划任务,而控制面板中的“任务计划”可以查看它和at命令定制的任务;二者都依靠task scheduler服务,如果该服务停止,通过运行“任务计划”中的任务可以开启该服务,而at命令定制的服务则不行。
例:设置at制定的任务为前台运行
at 16:30 /interactive c:\test.bat
/interactive 可使任务变为前台运行
例:指定时间运行某程序
At 16:00 c:\test.bat
::在16:00运行test.bat
例:没有15执行某任务
At 16:30 /every:15 c:\test.bat
::每月的15日16:30运行
At 16:30 /next:15 c:\test.bat
:: 下个月的15日16:30运行
At 16:30 /every:四 c:\test.bat
::每周四的16:30运行
例:删除某任务
At 2 /delete /yes
::删除任务ID为2的计划任务,/yes表示删除任务不需要确认
例:删除所有任务
At /delete
::不输入任何ID,表示清除所有计划任务
53.shutdows
Shutdown /s /t time /f
/s 指定关机操作
/t 多长时间后关机,如/t 6,6秒钟后关机
/f 强制关机,不管还有什么程序在进行
例:在指定的计算机上运行某程序
At \\computername 16:30 c:\test.bat
54.find
标准格式 find “要查找的字符串” 待查找的文本文件
例:在test.txt中查找nihao字符串
find “nihao” test.txt
Find /c “nihao” test.txt
::/c(count) 统计nihao在test.txt出现的次数
Find /n “nihao” test.txt
::/n(number) 统计所有nihao所在的行数
Find /i “nihao” test.txt
::/i(ignore)忽略大小写
Find /v “nihao” test.txt
::/v 查找不包含nihao字符串的内容
55.Shift
增加批处理中参数的数量
56.Systeminfo
如果需要批处理显示有关系统信息,该命令很有用。
57.Ntsd
强制关闭进程命令,例:ntsd –c q –pn notepad.exe
58.建立隐藏用户
之前掌握注册表的用法:
1利用net新建用户;2导出注册表SAM下的name项;3删除新建用户;4导入已导出的注册表
新方法:net user zgktest$ /add,此时,用net user是无法查看到新建用户的;为新建用户添加注释:net user zgktest$ /comment:”注释内容”
59.Sfc
扫描受保护的系统文件的完整性
/scannow :立即扫描所有受保护的系统文件,如有修改自动修复。
/verifyonly :仅扫描不修复
/verifyfile :仅扫描指定的文件不修复
59.Taskkill
终止进程
/f 强行终止
/im 指定终止进程的图象名
例:taskkill /f /im ctfmon.exe /im notepad.exe
三、批处理命令简介
1.Echo on/off
打开或关闭回显
echo off 表示不显示它以后的所有命令行
Echo 显示信息
Echo y|format a: 表示传递参数y
Echo n|format a:
以下是echo空行特殊写法
Echo.
Echo+
Echo;
例:echo nihao
@echo nihao
Pause
执行结果:
echo nihao rem 显示第1行命令行本身
nihao rem 显示第1行命令行执行结果
nihao rem显示第2行命令行执行结果
2.@
不显示命令行本身
3.Call
在一个批处理文件中调用另一个批处理或文件
例:在1.bat中调用2.bat
1.bat
@echo off
Echo this is 1.bat
Call 2.bat
::此时,用command /c 2.bat代替call 2.bat,不行,如果1.bat或2.bat中有中文,则显示一堆乱码
::用start 2.bat代替call 2.bat,执行完毕根本不返回到1.bat。
Echo 2.bat end,back to 1.bat
4.Pause
按任意键暂停
5.Goto label 和:label连用
注意label的命名有讲究,如果批处理中有多个label,那么label名的前八位字母就不能完全一致,因为COMMAND只识别前八位,如果命名一致,从第2个label将永远不能执行。
6.Rem
注释,等同于 ::和/* */
7.%
参数表示符
参数是指运行批处理文件时在文件名后加的字符串,范围%0~%9,%0表示文件本身,字符串由%1~%9
8.If
条件判断语句
If (not) /i “字符串1”=”字符串2” 待执行的命令
/I :表示不区分大小写判断
例:@echo off
Set /p var1= please input
Set /p var2= please input
If "%var1%"=="%var2%" (echo 变量相等) else echo 变量不相等
::变量var1和var2使用了双引号,是为了比较变量中的空格,如var1=a,var2=a ,不加
::双引号,它们相等,执行的是(echo 变量相等),加了双引号,执行的则是“else echo 变量不相等”命令
pause
If (not) exist 文件 待执行的命令
例:if exist c:\test1.txt (echo 存在test1.txt) else echo test1.txt不存在
If (not) errorlevel 数字 待执行的命令
例:@echo off
Set /p commandname=请输入要测试的是否存在命令
If errorlever==0 (echo 命令成功执行) else echo 命令没有成功执行
::曾经错误errorlever和0之间忘记了= =,echo和显示的信息之间没有空格
pause
例: @echo off
if not exist d:\myfolder\nul md d:\myfolder
if not exist d:\myfolder\word\nul md d:\myfolder\word
REM 在win98系统中,if语句无法检测到目录的存在,但可以检测空设备,所以为保证脚本正常运行,使用了nul。
If defined xxx command :判断xxx是否是被定义的变量
例:@echo off
Set var=123
If defined var (echo var是被定义的变量) else echo 未被定义
pause
If defined %var% (echo %var%是被定义的变量) else echo %var%是未被定义
::对var的值进行判断是否为变量
pause
Set 123=456
If defined 123 (echo 123是被定义的变量) else echo 未被定义
pause
9.Choice
Choice /c:参数 参数表示可输入的字符,由set /p代替,已经很少用
10.For
循环命令
FOR [%%f] in (集合) DO [命令]
/d 仅对目录操作有效,对文件无效
例:@echo off
for /d /r %%i in (*) do @echo %%i
::列出当前目录中的所有未隐藏的目录,文件不操作
pause
/r 递归(即对当前目录操作,其下的所有子目录也进行操作)
例:@echo off
for /d /r %%i in (*) do @echo %%i
::列出当前目录及其子目录中的所有未隐藏的目录,文件不操作
pause
/l 迭代数值范围
例:@echo off
for /l %%i in (1,1,5) do @echo %%i
pause
/f 读取文本中的每一行内容赋值给变量或将命令的执行结果返给变量(很常用)
例:有一文本test.txt,内容为:
姓名 关系
; 显示对应关系
张仪 劳动
得 顾主
@echo off
for /f "eol=; tokens=1,2 delims= " %%a in (c:\test.txt) do @echo %%a %%b
::读取文本的内容赋值给变量%%a,之后显示文本中的两列内容,带分号的行不显示
::eol=;表示忽略以分号;开头的行,即使不写该参数,也默认执行该参数
::tokens=1,2表示打印/显示文本的第1,2列内容
::delims= 表示以空格为分隔符
Pause
例:@echo off
for /f "eol=; tokens=1,2 delims= " %%a in (‘net user’) do @echo %%a %%b
~I 表示删除引号
删除首尾的引号
删除开头的引号
尾部的和中间的引号不删除
例:有一test.txt文档,内容如下:
“afds”
“daf
Dfs”
Afd”dfa
执行以下代码
@echo off
for /f %%a in (c:\test.txt) do @echo %%~a
pause
结果如下:
afds
daf
Dfs”
Afd”dfa
%~fi 表示将%i扩展到一个完全合格的路径
例:@echo off
for /f %%i in ('dir /b') do @echo %%~fi
pause
%~di 表示将%i 扩展到一个磁盘驱动器号
%~pi 表示将%i扩展到路径
%~ni 表示将%i扩展到文件名
%~xi 表示将%i扩展到文件后缀
%~si 表示将%i扩展到文件短名
例:@echo off
for /f %%i in ('dir /b') do @echo %%~si
pause
如果根目录有documents and setting,则只显示documents这样形式的文件短名
%~ai 表示将%i扩展到文件属性
%~ti 表示将%i扩展到文件的大小和日期
%~zi 表示将%i扩展到文件的大小
%~$path:I 表示在指定的path下搜索指定的文件
例:@echo off
for /f "delims=" %%i in ("ping.exe") do @echo %%~$path:i
::曾经犯的错误,括号里使用双引号而不是单引号
pause
11.,
相当于空格
例:在CMD下执行dirc:会出现错误提示,使用dir,c:则不会
12. “ “
界定符,常用来界定“带空格的目录”
例:在CMD下执行dir c:\documents and setting会出现错误提示,使用dir “c:\document and setting”则不会
13. ^
转义字符,取消特殊符号的作用
例:如果想将>这个特殊符号写到文本文件中去
echo > >test.txt 错误
Echo ^> >test.txt正确,取消了>特殊符号的输出重定向功能
14. &
命令连接字符,不管&之前的命令执行正确与否,其后的命令都会顺序执行
15. &&
命令连接字符,只有&&之前的命令执行正确,其后的命令才会执行
16. ||
命令连接字符,只有||之前的命令执行错误,其后的命令才会执行
17. |
管道命令
把前一个命令的输出结果作为下一个命令的输入
18. >
输出重定向命令
把前一个命令的输出结果写到后面的设备中去,后面设备的内容被覆盖
19. >>
输出重定向命令
把前一个命令的输出结果写到后面的设备中去,后面设备的内容不被覆盖
20. <
输出重定向命令
把后一个设备的指定内容作为前一个设备的输入
21. *和?
通配符
*表示任意多个字符
?表示任意一个字符
22. 概念理解:变量扩展与延迟变量扩展
变量扩展:在批处理的执行中,用变量的值替换变量的名的过程。
延迟变量扩展(使用标志setlocal enabledelayedexpansion)
例:@echo off
for /l %%i in (1,1,5) do (
set var=%%i
echo %var%
)
Pause
::代码解读,该代码段的执行结果显示“5个echo处于关闭状态”
::为什么呢?
::因为CMD执行批处理时首先是将每一个命令行读入内存进行匹配
::匹配的含义是检查命令行是否有语句格式的错误,而不是执行命令行
::红色代码是一行命令行
::变量var首先进行匹配而不能执行,所以此时var还没有被赋值,是空值
例:@echo off
setlocal enabledelayedexpansion
for /l %%i in (1,1,5) do (
set var=%%i
echo !var!
)
Pause
::代码解读,该代码段的执行结果显示“数列形式的1 2 3 4 5”
::为什么该代码段执行正确?
::因为它使用了“延迟环境变量扩展”
::延迟环境变量扩展中的变量用“! !”而不是“% %”
::使用延迟环境变量扩展的目的是先执行1次命令行在进行匹配
::因此,变量var先被赋值为1,之后匹配命令行
同理:
set var=test & echo %var% 会出现错误提示:echo处于关闭状态
setlocal enabledelayedexpansion
set var=test & echo !var! 被正确执行
23.;
当命令相同时,可以将不同目标分隔开
例:dir c:\;d:\;e:\相当于dir c:\ dir d:\ dir e:\
补充:
autoexec.bat :开机时自动运行的批处理文件
winstart.bat :选择进入windows状态时自动运行的批处理文件
Dosstart.bat :在windows下重新启动进入MS-DOS时自动运行的批处理文件
区别:执行的时间段不同
四、技巧集合
1.*.*可用.代替
Del *.* equ del .
2.无论命令是否正确执行,都屏蔽它的显示信息可将命令重定向到空设备NUL上
例:dir >nul 2>nul
3.向文本中添加内容
Type con >>文本名 REM 已测试,按F6键或CTRL+Z停止输入
Type con >filename equ copy con filename
type nul>filename 表示将文件内容清空,但filename的属性不能是只读和隐藏文件
4.DOS下的指法练习
Copy con nul
5.Regedit /e
导出注册表,例:regedit /e test,将注册表数据库导出到文件test.reg中
导入注册表,例:regedit/c test.reg,将test.reg导入到注册表中
例:regedit test.dat,将test.dat导入到注册表中
6.在“运行”或CMD下,直接运行“hh ntcmds.chm”,会启动“命令行参考”窗口,方便自学DOS命令
7.2>nul
2表示错误消息句柄
8.让程序一个接一个执行
start /w 第一个程序
start 第二个程序
9.查看与本地机器连接的用户列表
Net session
清除已经与本地连接的用户temp
Net session \\temp /delete
10.在子网内,ping不通网关,但可以与其它机器正常ping通
解决思路:获得网关正确的MAC地址,之后执行
arp -a 网关IP 网关MAC地址
11.新建一个文件
type nul>new.txt
例:建立批处理文件的方法总结
a. type nul>test.bat (test.bat空内容,需要进入编辑内容)
b. copy con test.bat
c. echo dir c:>test.bat
echo dir d:>>test.bat
d. edit test.bat
edlin test.bat
e. 在Windows下建立文本文件再改扩展名(需要进入编辑内容)
12.命令提示符被禁止
解决思路:reg delete HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows /f >nul
13.批处理执行遇到“bad command or filename”这样的错误提示该如何理解?
命令错误;
命令正确,但不在当前目录和PATH设置的搜索路径内;
批处理文件内容中有COMMAND无法解释的字符。
14.在用批处理编写菜单时,不要用特殊符号,如:| ,会引起歧义,造成错误。
15.想同别人QQ,可借鉴如下代码:Set/p qq=请输入你想和他/她聊的QQ号码(然后回车):
start tencent://Message/?Uin=%qq%
16.如何在批处理中加空行
@echo off
echo first^
echo second
rem ^是转义字符,可以将空行转义,其实自己也不太懂,但这个方法可行?
17.批处理中如何调用vbs文件(未测试)
start "" a.vbs 或 start c:\a.vbs
批处理中如何安装inf文件(在“工具”“文件夹选项”“文件类型”高级下查看“编辑”获取相关内容)
rundll32.exe setupapi,InstallHinfSection DefaultInstall 132 c:\b.inf
18.如果用Cacls把硬盘锁定了的解决方法
Cacls D: /t /c /g dfdgdfghfh:f rem 解锁D盘
19.设置本机“用户帐户”操作
control userpasswords2
五、断章取义
1.@echo msgbox "下载完了",4096 >> e:\test.vbs
start e:\test.vbs
REM 4096的含义是:系统模式:在用户响应消息框前,所有应用程序都被挂起
2.在批处理中加弹出窗口
a、Msg %username% /time:5 “hello,zgk”
REM 需TermService服务支持;/time:5表示弹出窗口停留时间;“hello,zgk”表示弹出窗口的内容。
b、net send %computername% “弹出窗口显示内容” >nul
REM 需message信使服务支持
c、利用系统自带的mshta程序
利用vbscript自带的msgbox函数显示
mshta vbscrip:msgbox(“弹出窗口具体内容显示”,64,”弹出窗口标题”)(windows.close)
REM 64表示弹出窗口停留时间,windows.close表示停留64秒后关闭窗口
d、利用vbscript的popup功能
mshta vbscript:CreateObject("Wscript.Shell").popup("窗口显示内容",7,"窗口标题",64)(window.close)
e、mshta javascript:window.alert("警告窗口信息");window.close()
f、利用javascript的popup功能
mshta "javascript:new ActiveXObject('WScript.Shell').popup('Hello,lxmxn',7,'batch script',64);window.close();"
g、利用javascript的confirm功能
mshta javascript:confirm("ha");window.close()
3、不断弹出窗口的代码
@echo off
Start notepad.exe
%0
Rem 试了一下,确实挺狠,只有重新启动机器
4、设定循环次数启动某程序或命令
@echo off
:loop
If not exist c:\test.txt echo. >c:\test.txt &goto err1
If not exist c:\test1.txt echo. >c:\test1.txt &goto err1
If not exist c:\test2.txt echo. >c:\test2.txt &goto err1
If not exist c:\test3.txt echo. >c:\test3.txt &goto err1
:err1
Start notepad.exe
Goto loop
Rem 其实还可以用其它方法实现,只为学习!
5、记录登陆计算机时间的批处理
@echo off
Date /t >record.txt
Time /t >>record.txt
Attrib +s +h record.txt
Attrib +s +h record.bat
最后,把record.bat加入到注册表中的如下位置:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon]
"Userinit"="C:\\WINDOWS\\system32\\userinit.exe,record.bat,"
注意:根据record.bat的实际路径书写,记住,它后面的逗号,不能不写!
9、隐藏运行批处理文件时“一闪而过的CMD窗口画面”
方法一:利用JS代码
new ActiveXObject('WScript.Shell').Run('cmd /c 隐藏的.bat',0);
方法二:利用VB代码
Set ws = CreateObject("Wscript.Shell")
ws.run "cmd /c felix.bat",vbhide
方法三:利用VB代码
CreateObject("WScript.Shell").Run "cmd /c felix.bat",0
10、将某个文件拷贝到某个磁盘所有目录包括子目录下
@echo off
for /r D: %%i in (.) do copy /y 01.txt "%%i"
pause
REM 将01.txt拷贝到D盘下的所有目录
11、如何更干净的清除垃圾文件
关注 cookies、temp、tempor~1、history等目录和win386.swp和注册表信息
12、安静模式运行程序的脚本代码
On Error Resume Next
set wshshell=createobject("wscript.shell")
a=wshshell.run ("文件名",0)
rem 其中的文件名就是要运行的程序,0就是程序运行时不显示运行窗口
13、删除found.001/found.002等垃圾文件的批处理代码,不错!
for %%a in (c d e f g) do (
for /r %%a:\ %%i in (FOUND.00*) do (rd /s /q %%i >nul 2>nul)
)
14、清除重复行批处理代码
@echo off
for /f "delims=" %%i in (a.txt) do (
findstr /c:"%%i" b.txt 2>nul||echo %%i>>b.txt
)
Pause
rem 为何能实现?
rem 比如a.txt内容为“张三 李四 张三”三行,那么在将张三赋给变量%%i,后
rem 再执行在b.txt中查找“张三”,没有找到说明第2行语句前半段错误,所以
rem ||后的命令得以执行,那么第2次将“张三”赋给%%i再在b.txt中查找张三
Rem 就能够查到,语句正确,后者命令就不能执行,不知解释的是否正确
17、通过批处理修改注册表中的文件类型进而实现“某类型文件无法被打开”?
@echo off
reg add HKCR\.bat /f /ve /d bat >nul 2>nul
reg add HKCR\.cmd /f /ve /d cmd >nul 2>nul
echo.
echo 啊哦,bat/cmd文件无法打开或者编辑了!
pause >nul
Rem bat和cmd后缀类型的文件就无法被打开了,如果需要打开它们可恢复注册表,rem 当然前提是有注册表备份了
六、概念理解
1.什么是MD5:MD5的全称是Message-Digest Algorithm 5(信息-摘要算法),它能将一串随机长度的信息(当然也包括文件)通过其加密函数算法生成一个惟一的128位值,相同信息的MD5值也是相同的,反之,文件即使略有改动,其MD5值也会产生变化。因此,只需比较文件的MD5值,就能知道文件是否经过改动了。
七、DEBUG的学习
H
:代表十六进制,DEBUG使用的是H,通过DEBUG可以建立工具用于批处理的使用。
学习示例:
在CMD下建立一“打印屏幕内容的工具”
Debug scrprint.com
rem scrprint.com是即将要建立程序或者说是工具
-a 100
rem –是debug的输入标志, “a 100”表示在以十六进制地址100所指定的地址输入命令
0b06:0100 100 int 5
rem 输入命令int 5,“int 5”表示将打印屏幕内容
0b06:0102 mov ah,4c
0b06:0104 int 21
rem 以上两条命令是表示通知MS-DOS,结束程序
0106 按ENTER
-r cx
rem cx是Debug用来存放程序大小的寄存器
:6
rem 6是该程序的大小,计算程序大小的方法是最后一行地址0106减去第一行地址0100,是6个字节
-w
rem 将程序写入到磁盘中
-q
Rem 退出MS-DOS
2007-12-03
Why Learn DOS When There's Windows?
Because DOS is more efficient in some aspects; learning Linux, it's more convenient to use DOS for switches/routers; for remote control.
I. Introduction and Overview
1. Files and Directories
File name: file base name + suffix
File base name: 1 - 8 characters, must exist for the file name; suffix: 0 - 3 characters, optional.
Directory: Called "folder" in Windows.
When displayed with DIR, it has the mark, indicating they are directories.
2. .exe: Executable file
.com: Command file
.bat: Batch file
They are all called "executable files".
The priority of the .bat suffix file is higher than those with .exe and .com suffixes.
3. Internal and External DOS Commands
Internal commands are directly loaded into memory by command.com when the system starts and can be used directly.
In other words, internal commands exist in the command.com file.
External commands are independent files existing on the disk and can be loaded into memory for execution when needed.
4. . and .. and \
. : Current directory
.. : The upper-level directory of the current directory, also called "parent directory"
\ : Root directory.
5. Dir Command
When the current directory has . and .., when using the dir command to display the current directory information, they are considered as a file, just with a size of zero.
6. DOS Boot Sequence
Boot -> IO.SYS -> MSDOS.SYS -> CONFIG.SYS -> COMMAND.COM -> Autoexec.bat
Among them, IO.SYS, MSDOS.SYS, and COMMAND.COM are essential for the startup of the DOS system.
io.sys: Input/output processing program
Msdos.sys: File processing program
Command.com: Command processing program
New Explanation:
For DOS, when the hard disk boots, the INT19 interrupt first reads the "hard disk MBR". After reading, it is loaded into memory at 0000:007c, and then INT19 also jumps to 0000:007c in memory. At this time, the control right is still INT19. Then, a "program" in the MBR will look for the "bootable partition". After finding it, the bootable partition is loaded into 0000:007c. Then the MBR program will jump to the address 0000:007c, and the system starts to boot.
The main boot sector is: cylinder 0, head 0, sector 1
Then comes the FAT (File Allocation Table)
Supplementary (2007-12-10)
. DOS: disk operating system, single-user single-task OS.
Cold boot: When starting the computer, turn on the monitor power -> host power, and the shutdown is in the reverse order.
Warm boot: When the system is started, press the CTRL+ALT+DEL key combination to start the system again.
Difference between the two: Whether to skip some hardware detection processes such as memory detection, and other running processes are the same.
. Common Reserved Names in DOS
CON: Keyboard/display
NUL: Empty device or virtual device
AUX/COM1: First serial communication interface
COM2\COM3\COM4: 2nd, 3rd, 4th serial ports
LPT1\PRN: First parallel interface
. A batch file can be understood as "a DOS command".
. Why Not Name a Batch File as an "Internal Command or External Command" of DOS?
Answer: If it has the same name as an internal command, then the internal command has a higher priority than the batch, and the batch file cannot be executed;
If it has the same name as an external command, it depends on "whether the external command or the batch file is found first". The one found first is executed first. Therefore, it is recommended to avoid naming batches the same as internal and external commands of DOS.
. How to Create a Batch File in DOS?
a. copy con the batch file to be created
b. edit the batch file to be created
. Also can use
Pause the information to be displayed, similar to echo the information to be displayed
. How to Make a "Batch File" Beep? (Relying on the built-in speaker of the computer)
In DOS, use edit beep.bat, then enter the editing page, first enter Pause, then enter a space, then hold down the CTRL key, press the "P" key, release the CTRL key, then hold down the CTRL key, press "G", and a "beep control character" can be generated.
It can also be done by holding down the CTRL key and pressing "P" and "G" keys successively.
In fact, echo can also achieve the same effect, but it is troublesome to input the control character in the text. It is a good way to edit the batch file in DOS, input the control character and save it, then return to Windows to edit.
II. Introduction to DOS Commands
1. Dir
Displays the current directory information but does not include system and hidden files.
dir /p: Display information in pages (p is the abbreviation of page, that is, display screen by page)
dir/w: Display information in a wide list, without file size and creation date
dir/d: Similar to dir/w display mode
dir/b: Only display file names, directory names are also displayed in the form of file names, and the mark of directory names is not displayed (a concise display)
dir /l: Display files and directories in lowercase letters
dir /a: Display files with specified attributes, for example: dir /a:r displays all files with read-only attributes in the current directory
Example: dir /a:d means only display directory information
Example: To find files of a specified date, dir|find "2007-12-04", pay attention to the writing format of the date to match the local date display
Example: To find files in multi-level directories, use the parameter /s, such as dir temp /s. If there is a temp directory under the current directory and there is a temp directory under temp, the execution result is to list all files in the last-level temp directory
REM
dir/? to see help, find that the : after a is optional, but if : is not used, the message "The volume of the current drive has no label, and the file is not found" will be displayed.
Why does it work without :? I made a mistake myself!
Dir /a:-r: Display all files with non-read-only attributes in the current directory
- : Represents the "prefix of no".
REM
Dir /o: Display information in a classified way, such as file size, alphabetical order, etc. For example: dir /o:s means display information according to file size; dir /o:n displays information according to alphabetical order
Dir /n: Display in "long file list mode, file name on the rightmost side"
Dir /c: Similar to dir/n
Dir/x: Display files not in the 8dot3 naming rule
Example: dir >test.txt means import the result of the dir command into a text file
2. Cd
Change directory
Note: If the following command is used on the C drive
c:\>cd e:\test
The result is still at c:\>, but it is transferred to the D drive, and the current directory of the D drive is d:\>test>. I encountered the above problem when using at to regularly delete files in a certain directory.
Example:
@echo off
c:
rem At that time, I forgot to go to c:, and as a result, many files on the disk where the batch file was located were deleted, including the batch file itself
rem Making the at task unable to execute
cd "C:\Documents and Settings\All Users\Application Data\Symantec\Symantec AntiVirus Corporate Edition\7.5\Logs"
echo y | del *.*
Cd .. means go back to the upper-level directory
Cd\ means go back to the root directory
Cd /d parameter /d means change both the current directory and the current drive
3. Copy
The function is to copy and move, but cannot copy subdirectories in the directory
Example: Merge two text files 1.txt and 2.txt into 3.txt
Copy /a 1.txt+2.txt 3.txt
REM Merge these two files according to ASCII code
Copy /b 1.txt+2.txt 3.txt
REM Merge these two files according to binary code
Parameters /a and /b cannot be used together. Among them, /a can only merge plain text files, and /b can merge in both text and binary ways
Example: Encrypt a file
copy /b test.jpg+1.txt 2.jpg
REM test.jpg and 1.txt become a file 2.jpg, so the text information is encrypted. To view this information, you can use the ultraedit software to view
REM Remember, the document to be encrypted must be placed on the right side of the + sign
4. Xcopy
Can copy non-empty subdirectories in the directory to other places, but need to use the parameter /s
/e must be used with parameter /s, indicating that not only subdirectories can be copied, but also empty directories can be copied
/v Verify after copying
5. Del
Delete
Del *.* is a very dangerous command
Example: del /f Force delete read-only files Del/a Delete files with specified attributes
6. ren
Rename
7. type
Can only display the content of one file at a time
8. Format and unformat
The available space of the formatted disk is equal to the total space of the disk, indicating that the disk performance is good
Format /u means unconditional formatting, at this time unformat is invalid
Example: Echo y|formant a:
Unformat drive letter means restore the formatted disk
unformat /l means list the recoverable file list
9. Md and Rd
Create a new directory
Example: Create multiple directories at the same time
md c:\1 d:\2 e:\3 is equivalent to md c:\1;d:\2
Delete the directory. The directory to be deleted cannot have subdirectories and files. If you want to do this, you can use
Rd /s
Example: Create an encrypted directory and how to view and delete it
md test..\
This creates an "encrypted" folder, which cannot be opened by double-clicking
It can be viewed through "Run" in the Start menu or the address bar in Explorer by entering its "complete path"
Delete it through rd /s /q
Thought: If the "encrypted" folder established is combined with the method of hiding attributes including registry hiding, a relatively private space can be established.
Approximate location of the registry: MACHINE\SOFTWARE\WINDOWNS\CURRENTVERSION\EXPLORER\ACVANCED\FOLEDR\SHWOALL\CHECKEDVALUE's value
10. Deltree
Delete the directory tree, and it deletes non-empty directories without hesitation
Deltree *.* is a very dangerous command
11. Mem
Memory
12. Chkdsk
Checkdisk
13. Sys
C:\>sys a: is equivalent to format a:/s, both are to make a bootable disk
If you copy a DOS bootable disk, the two files io.sys and msdos.sys may not be copied to the frontmost track of the disk
14. Cls
Clear screen
15. More
Display in pages
16. Move
Example: @echo off
Cd c:\test
Move c:*.* a:
REM
Note that there is no "\" between the 3rd line "c: and *.*", which means to copy all files in the current directory, that is, the test directory, to the A drive.
17. Help
As its name implies
18. Attrib
Attribute
Example: Set all files and subdirectories (including the directory itself) in the c:\test directory to "read-only" attribute
Attrib +r c:\test /s /d
/s: Indicates to operate on subdirectories
/d: Indicates to operate on directories, which can be simply understood as directory
Example: Set all files and subdirectories (excluding the directory itself) in the c:\test directory to "read-only" attribute
Attrib +r c:\test\*.* /s /d
19. Time and date
Date /t: No need to input a new time
Echo+|date|find "current date"
Echo+|time|find "current time"
Example: A batch file can be written to record the time usage of the machine
echo+|date/t>test.txt
echo+|time/t>>test.txt
20. Lable
21. Defrag
Defragment the disk
22. Doskey
Establish and call DOS macro commands
Example: doskey d=deltree, then executing d is equivalent to executing the deltree command
Example: If a lot of commands are input in CMD and you need to use these commands again without repeating input, you can use doskey. The specific operation (in CMD): doskey /h (h is history) is to view the commands that have been used in CMD before, and they can be called again through the F9 key to call their cache table, or the up and down arrows or PaUp and PaDn keys can be used to operate. If you want to clear them, you can use doskey /reinstall.
23. Fdisk
Fdisk /mbr: Re-establish the DOS main boot record
24. Memmaker
Memory optimization command
25. Emm386
Extended memory management
26. Lh or loadhigh
Load the program into the upper memory
27. Msd
System detection
Cannot be used directly
28. Undelete
Before using this command, you need to use the lock command to remove the restriction that the hard disk directory area cannot be modified
Undelete /all: Restore all del files without asking
Undelete /list: List the recoverable file list
29. Path
Example: path c:\test
If a command is executed in the current directory and it does not exist, it will continue to look for the command in the path-set path, and execute it if it exists
30. Prompt
Set the prompt, which is the common c:\> we see. c: indicates that the current drive letter is C drive, \ indicates the root directory, and > separates the prompt from the command to be input.
It can be changed according to needs
31. Backup and restore
Backup and restore
Restort /s: Restore subdirectories to the specified directory
32. Edit
Can only edit text files. If the edited file exists, it will be edited. If it does not exist, it will be temporarily created and enter the editing state. If saved, the file will be established on the disk
33. Set
Set variables. Enter the set command directly in CMD, and most system variables will be listed
Example: set path=c:\test is equivalent to path c:\test
Example: Manually input variable value
set /p a= Please input your choice
REM In the pure DOS environment, the /p parameter does not exist, and this statement is naturally not good!
REM You can define a variable similar to a system variable (a variable that still exists after restarting the machine) through the setx command. However, this command does not exist in the XP system, but exists in 2003. Format: setx variable assignment
Set /a var=
REM Arithmetic operation on variables
Example: set /a var+=1
Set %path:str1=str2%
REM Replace str1 with str2
Example: @echo off
set var= zgk.com
Echo Display the original value of var
echo %var%
pause
set a=%var: =%
rem The space in the original variable is replaced
echo Display the value of the replaced var
echo %a%
set b=%var:.=%
echo %b%
rem The dot "." in the original variable is replaced
pause
set %path:~10,5%
REM Intercept the specified number of columns of the variable
Example: @echo off
Set var=zgk.com
Echo %var%
Set b=%var:~2,3%
rem Intercept the first 2 columns of the specified variable var, that is, start reading 3 characters from the 3rd column and assign them to the new variable b, rem then b=k.o
Echo %b%
Pause
Set %path:~-10%
Example: @echo off
set var=zgk.com
Echo %var%
Set b=%var:~-3%
rem Take 3 columns from the back of the specified variable var and assign them to the new variable b, then b=com
Echo %b%
Set c=%var:~3%
rem Intercept the first 3 columns of the specified variable var from the beginning, that is, assign all variables after the 4th column of var to c, rem then c=.com
Echo %c%
pause
Set %path:~0,-2%
Example: @echo off
set var=zgk.com
Echo %var%
Set b=%var:~-3%
rem Take 3 columns from the back of the specified variable var and assign them to the new variable b, then b=com
Echo %b%
Set c=%var:~0,-2%
rem Remove 2 columns from the var from the back, then assign var to c, then c=zgk.c
Echo %c%
pause
34. Smartdrv
Set disk cache
35. Append
Set non-executable file path
Example: There is no test.txt in the current directory, and there is in c:\
append c:\ is similar to the path command
36. Debug
Debug file name
37. Diskcomp
Compare the contents of two floppy disks
38. Expand
Unzip command
Expand original compressed file path destination
39. Fc
Compare the contents of two files
Example: fc /c test1.txt test2.txt
rem /c Compare case-insensitively
40. Fasthelp
Quick help
Not available in the XP system
Fashhelp command is equivalent to command/?
41. Qbasic
Start the basic integrated environment
42. Setver
Set version, and can also view the versions of winword and excel
The common syntax in config.sys: device=setver.exe
REM
When device=setver is not added in config.sys, the versions of winword and excel can still be seen. Why can't anything be seen after adding it? There is no error message
REM
43. Share
44. Subst
Replace a certain drive letter with a specified path
Example: subst a: c:\test means replace the A drive with the test directory under the C drive
Subst a: /d means delete the replacement
45. Tree
Display the structure of all subdirectories under the current directory or specified directory, but does not display file names
/f (file): Display the directory and the file names under the directory at the same time
Tree /a: Display the directory tree in ASCII code
Example: To find the number of test.txt in the c:\test directory
tree /f c:\test | find /c /I "test.txt"
If there are too many files exceeding the buffer size, you can use: tree /f |more
46. Vsafe
Virus protection program, not tried!!!!!
47. Ver
View the DOS version number
48. Vol
View the volume label of the disk
49. Ctty
Change the input and output device of the control
Example: ctty aux means set aux as the input and output device
50. Recover
Overwrite the disk
51. Replace
Example: replace c:\test1.txt d:\test2.txt /r
Even if test2.txt has the read-only attribute, it will be replaced
Example: replace d:\a.txt d:\backup /s /p /u
/s: Replace all files with the same name in D:\backup and its subdirectories with D:\a.txt
/p: Confirm before replacing
/u: (update), check the modification time of the source file and the target file before replacing. If the former is newer, it will not be replaced
Example: @echo off
cd %1
for %%i in (*.%3) do if not exist "%2%%i" copy %%i "%2" /y
replace *.%3 "%2" /u
Execute filesyn.bat d:\ e:\ txt
52. at
Customize scheduled tasks (the scheduled tasks customized by this command run in the background, while the tasks customized by "Task Scheduler" in Windows run in the foreground). The main difference between the two is that the at command can only view the scheduled tasks customized by the at command itself, while "Task Scheduler" in the control panel can view it and the tasks customized by the at command; both rely on the task scheduler service. If this service is stopped, running the tasks in "Task Scheduler" can start this service, but the tasks customized by the at command cannot.
Example: Set the task customized by at to run in the foreground
at 16:30 /interactive c:\test.bat
/interactive can make the task run in the foreground
Example: Run a program at a specified time
At 16:00 c:\test.bat
:: Run test.bat at 16:00
Example: Run a task at 15
At 16:30 /every:15 c:\test.bat
:: Run at 16:30 on the 15th of each month
At 16:30 /next:15 c:\test.bat
:: Run at 16:30 on the 15th of next month
At 16:30 /every:Thursday c:\test.bat
:: Run at 16:30 every Thursday
Example: Delete a task
At 2 /delete /yes
:: Delete the scheduled task with task ID 2, /yes means no need to confirm when deleting the task
Example: Delete all tasks
At /delete
:: Not entering any ID means clear all scheduled tasks
53. shutdows
Shutdown /s /t time /f
/s Specify the shutdown operation
/t How long to shut down after, such as /t 6, shut down after 6 seconds
/f Force shutdown, regardless of what program is running
Example: Run a program on a specified computer
At \\computername 16:30 c:\test.bat
54. find
Standard format find "string to find" text file to be searched
Example: Find the nihao string in test.txt
find "nihao" test.txt
Find /c "nihao" test.txt
:: /c (count) Count the number of times nihao appears in test.txt
Find /n "nihao" test.txt
:: /n (number) Count the lines where all nihao are located
Find /i "nihao" test.txt
:: /i (ignore) Ignore case
Find /v "nihao" test.txt
:: /v Find the content that does not contain the nihao string
55. Shift
Increase the number of parameters in the batch
56. Systeminfo
This command is useful if you need a batch to display system information.
57. Ntsd
Force close process command, for example: ntsd –c q –pn notepad.exe
58. Create a hidden user
Previously mastered the usage of the registry:
1. Use net to create a new user; 2. Export the name item under SAM in the registry; 3. Delete the newly created user; 4. Import the exported registry
New method: net user zgktest$ /add, at this time, the newly created user cannot be viewed with net user; add a comment to the newly created user: net user zgktest$ /comment:"comment content"
59. Sfc
Scan the integrity of protected system files
/scannow: Immediately scan all protected system files and automatically repair if there are modifications.
/verifyonly: Only scan and not repair
/verifyfile: Only scan the specified file and not repair
59. Taskkill
Terminate the process
/f Force terminate
/im Specify the image name of the process to terminate
Example: taskkill /f /im ctfmon.exe /im notepad.exe
III. Introduction to Batch Commands
1. Echo on/off
Turn on or off echo
echo off means not to display all command lines after it
Echo display information
Echo y|format a: means pass the parameter y
Echo n|format a:
The following are special ways to echo empty lines
Echo.
Echo+
Echo;
Example: echo nihao
@echo nihao
Pause
Execution result:
echo nihao rem Display the command line itself
nihao rem Display the execution result of the 1st command line
nihao rem Display the execution result of the 2nd command line
2. @
Do not display the command line itself
3. Call
Call another batch or file in a batch file
Example: Call 2.bat in 1.bat
1.bat
@echo off
Echo this is 1.bat
Call 2.bat
:: At this time, using command /c 2.bat instead of call 2.bat is not okay. If there are Chinese characters in 1.bat or 2.bat, a bunch of garbled characters will be displayed
:: Using start 2.bat instead of call 2.bat, it will not return to 1.bat after execution.
Echo 2.bat end,back to 1.bat
4. Pause
Pause by pressing any key
5. Goto label and :label used together
Note that there are requirements for naming the label. If there are multiple labels in the batch, the first eight letters of the label name cannot be exactly the same, because COMMAND only recognizes the first eight. If the names are the same, the second label will never be executed.
6. Rem
Comment, equivalent to :: and /* */
7. %
Parameter identifier
Parameters refer to the strings added after the file name when running the batch file, ranging from %0~%9. %0 represents the file itself, and the strings are from %1~%9
8. If
Conditional judgment statement
If (not) /i "string1"="string2" command to be executed
/I: Indicates case-insensitive judgment
Example: @echo off
Set /p var1= please input
Set /p var2= please input
If "%var1%"=="%var2%" (echo variables are equal) else echo variables are not equal
:: The variables var1 and var2 use double quotes to compare spaces in the variables. For example, var1=a, var2=a. Without double quotes, they are equal and (echo variables are equal) is executed. With double quotes, (else echo variables are not equal) command is executed
pause
If (not) exist file command to be executed
Example: if exist c:\test1.txt (echo test1.txt exists) else echo test1.txt does not exist
If (not) errorlevel number command to be executed
Example: @echo off
Set /p commandname=Please input the command to be tested whether it exists
If errorlever==0 (echo command executed successfully) else echo command did not execute successfully
:: Once made a mistake that errorlever and 0 were forgotten to be = =, and there was no space between echo and the displayed information
pause
Example: @echo off
if not exist d:\myfolder\nul md d:\myfolder
if not exist d:\myfolder\word\nul md d:\myfolder\word
REM In the win98 system, the if statement cannot detect the existence of the directory, but can detect the empty device, so to ensure the normal operation of the script, nul is used.
If defined xxx command: Judge whether xxx is a defined variable
Example: @echo off
Set var=123
If defined var (echo var is a defined variable) else echo not defined
pause
If defined %var% (echo %var% is a defined variable) else echo %var% is not defined
:: Judge whether the value of var is a variable
pause
Set 123=456
If defined 123 (echo 123 is a defined variable) else echo not defined
pause
9. Choice
Choice /c: Parameters indicate the characters that can be input, replaced by set /p, which is rarely used now
10. For
Loop command
FOR in (collection) DO
/d Only effective for directory operations, ineffective for files
Example: @echo off
for /d /r %%i in (*) do @echo %%i
:: List all unhidden directories in the current directory, and do not operate on files
pause
/r Recursive (that is, operate on the current directory, and all subdirectories under it are also operated)
Example: @echo off
for /d /r %%i in (*) do @echo %%i
:: List all unhidden directories in the current directory and its subdirectories, and do not operate on files
pause
/l Iterate over the numerical range
Example: @echo off
for /l %%i in (1,1,5) do @echo %%i
pause
/f Read each line of content in the text and assign it to a variable or return the execution result of the command to a variable (very commonly used)
Example: There is a text test.txt with the content:
Name Relationship
; Display the corresponding relationship
Zhang Yi Labor
De Employer
@echo off
for /f "eol=; tokens=1,2 delims= " %%a in (c:\test.txt) do @echo %%a %%b
:: Read the content of the text and assign it to the variable %%a, then display the two columns of content in the text. The line with a semicolon is not displayed
:: eol=; means ignore the line starting with semicolon ;, even if this parameter is not written, it is executed by default
:: tokens=1,2 means print/display the content of the 1st and 2nd columns of the text
:: delims= means use space as the delimiter
Pause
Example: @echo off
for /f "eol=; tokens=1,2 delims= " %%a in ('net user') do @echo %%a %%b
~I means delete the quotes
Delete the quotes at the beginning and end
Delete the quotes at the beginning
The quotes at the end and in the middle are not deleted
Example: There is a test.txt document with the following content:
"afds"
"daf
Dfs"
Afd"dfa
Execute the following code
@echo off
for /f %%a in (c:\test.txt) do @echo %%~a
pause
The result is as follows:
afds
daf
Dfs”
Afd”dfa
%~fi means expand %i to a fully qualified path
Example: @echo off
for /f %%i in ('dir /b') do @echo %%~fi
pause
%~di means expand %i to a drive letter
%~pi means expand %i to the path
%~ni means expand %i to the file name
%~xi means expand %i to the file suffix
%~si means expand %i to the short name of the file
Example: @echo off
for /f %%i in ('dir /b') do @echo %%~si
pause
If there is documents and setting in the root directory, only the short name of documents will be displayed
%~ai means expand %i to the file attribute
%~ti means expand %i to the size and date of the file
%~zi means expand %i to the size of the file
%~$path:I means search for the specified file in the specified path
Example: @echo off
for /f "delims=" %%i in ("ping.exe") do @echo %%~$path:i
:: Once made a mistake, use double quotes instead of single quotes in the brackets
pause
11.,
Equivalent to space
Example: Executing dirc: in CMD will have an error message, using dir,c: will not
12. " "
Delimiter, often used to delimit "directories with spaces"
Example: Executing dir c:\documents and setting in CMD will have an error message, using dir "c:\document and setting" will not
13. ^
Escape character, cancel the function of special symbols
Example: If you want to write the > special symbol into the text file
echo > >test.txt is wrong
Echo ^> >test.txt is correct, canceling the output redirection function of the > special symbol
14. &
Command connection character, regardless of whether the command before & is executed correctly, the command after it will be executed in sequence
15. &&
Command connection character, only if the command before && is executed correctly, the command after it will be executed
16. ||
Command connection character, only if the command before || is executed incorrectly, the command after it will be executed
17. |
Pipe command
Take the output result of the previous command as the input of the next command
18. >
Output redirection command
Write the output result of the previous command to the device behind, and the content of the device behind is overwritten
19. >>
Output redirection command
Write the output result of the previous command to the device behind, and the content of the device behind is not overwritten
20. <
Output redirection command
Take the specified content of the device behind as the input of the previous device
21. * and?
Wildcards
* represents any number of characters
? represents any one character
22. Concept understanding: Variable expansion and delayed variable expansion
Variable expansion: In the execution of the batch, the process of replacing the variable name with the value of the variable.
Delayed variable expansion (using the flag setlocal enabledelayedexpansion)
Example: @echo off
for /l %%i in (1,1,5) do (
set var=%%i
echo %var%
)
Pause
:: Code interpretation, the execution result of this code segment shows "5 echo are in the off state"
:: Why?
:: Because when CMD executes the batch, it first reads each command line into memory for matching
:: Matching means checking whether there is a syntax error in the command line, not executing the command line
:: The red code is one command line
:: The variable var is first matched and cannot be executed, so at this time var has not been assigned and is empty
Example: @echo off
setlocal enabledelayedexpansion
for /l %%i in (1,1,5) do (
set var=%%i
echo !var!
)
Pause
:: Code interpretation, the execution result of this code segment shows "1 2 3 4 5 in the form of a sequence"
:: Why does this code segment execute correctly?
:: Because it uses "delayed environment variable expansion"
:: Variables in delayed environment variable expansion use "! !" instead of "% %"
:: The purpose of using delayed environment variable expansion is to execute the command line once first and then match
:: Therefore, the variable var is first assigned to 1, and then the command line is matched
Similarly:
set var=test & echo %var% will have an error message: echo is in the off state
setlocal enabledelayedexpansion
set var=test & echo !var! is executed correctly
23. ;
When the commands are the same, different targets can be separated
Example: dir c:\;d:\;e:\ is equivalent to dir c:\ dir d:\ dir e:\
Supplementary:
autoexec.bat: Batch file that runs automatically when the computer starts
winstart.bat: Batch file that runs automatically when entering the Windows state
Dosstart.bat: Batch file that runs automatically when restarting into MS-DOS under Windows
Difference: The execution time periods are different
IV. Skill Collection
1. *.* can be replaced by.
Del *.* equ del .
2. To shield the display information of the command regardless of whether the command is executed correctly, redirect the command to the empty device NUL
Example: dir >nul 2>nul
3. Add content to the text
Type con >> text name REM Tested, press F6 key or CTRL+Z to stop input
Type con >filename equ copy con filename
type nul>filename means to clear the content of the file, but the attribute of filename cannot be read-only and hidden
4.指法练习 in DOS
Copy con nul
5. Regedit /e
Export the registry, for example: regedit /e test, export the registry database to the file test.reg
Import the registry, for example: regedit/c test.reg, import test.reg into the registry
Example: regedit test.dat, import test.dat into the registry
6. In "Run" or CMD, directly run "hh ntcmds.chm", which will start the "Command Line Reference" window, which is convenient for self-study of DOS commands
7. 2>nul
2 represents the error message handle
8. Make programs execute one after another
start /w first program
start second program
9. View the list of users connected to the local machine
Net session
Clear the user temp already connected to the local
Net session \\temp /delete
10. In the subnet, cannot ping the gateway, but can ping other machines normally
Solution idea: Obtain the correct MAC address of the gateway, then execute
arp -a gateway IP gateway MAC address
11. Create a new file
type nul>new.txt
Example: Summary of methods to create a batch file
a. type nul>test.bat (test.bat is empty, need to enter content to edit)
b. copy con test.bat
c. echo dir c:>test.bat
echo dir d:>>test.bat
d. edit test.bat
edlin test.bat
e. Create a text file under Windows and then change the extension (need to enter content to edit)
12. Command prompt is prohibited
Solution idea: reg delete HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows /f >nul
13. How to understand the error message "bad command or filename" when the batch execution encounters it?
Command error;
The command is correct, but it is not in the current directory and the search path set by PATH;
There are characters that COMMAND cannot interpret in the batch file content.
14. When writing a menu with a batch, do not use special symbols, such as: |, which will cause ambiguity and errors.
15. To chat with others on QQ, you can refer to the following code: Set/p qq=Please input the QQ number you want to chat with him/her (then press enter):
start tencent://Message/?Uin=%qq%
16. How to add an empty line in a batch
@echo off
echo first^
echo second
rem ^ is an escape character, which can escape the empty line. In fact, I don't understand it very well, but this method works?
17. How to call a vbs file in a batch (not tested)
start "" a.vbs or start c:\a.vbs
How to install an inf file in a batch (view relevant content in "Tools" "Folder Options" "File Types" Advanced under "Edit")
rundll32.exe setupapi,InstallHinfSection DefaultInstall 132 c:\b.inf
18. If the hard disk is locked with Cacls, the solution
Cacls D: /t /c /g dfdgdfghfh:f rem Unlock the D drive
19. Set the operation of the local "user account"
control userpasswords2
V. Taking Things Out of Context
1. @echo msgbox "Download completed",4096 >> e:\test.vbs
start e:\test.vbs
REM The meaning of 4096 is: System mode: All applications are suspended before the user responds to the message box
2. Add a pop-up window in a batch
a、Msg %username% /time:5 “hello,zgk”
REM Requires the TermService service support; /time:5 means the pop-up window stays for 5 seconds; “hello,zgk” means the content of the pop-up window.
b、net send %computername% “Content displayed in the pop-up window” >nul
REM Requires the message messenger service support
c、Use the built-in mshta program of the system
Use the msgbox function in vbscript to display
mshta vbscrip:msgbox(“Specific content displayed in the pop-up window”,64,”Title of the pop-up window”)(windows.close)
REM 64 means the pop-up window stays for 64 seconds, and windows.close means close the window after staying for 64 seconds
d、Use the popup function of vbscript
mshta vbscript:CreateObject("Wscript.Shell").popup("Content displayed in the window",7,"Title of the window",64)(window.close)
e、mshta javascript:window.alert("Warning window information");window.close()
f、Use the popup function of javascript
mshta "javascript:new ActiveXObject('WScript.Shell').popup('Hello,lxmxn',7,'batch script',64);window.close();"
g、Use the confirm function of javascript
mshta javascript:confirm("ha");window.close()
3. Code that continuously pops up windows
@echo off
Start notepad.exe
%0
Rem Tried it, it's really fierce, only restart the machine
4. Set the number of loop times to start a program or command
@echo off
:loop
If not exist c:\test.txt echo. >c:\test.txt &goto err1
If not exist c:\test1.txt echo. >c:\test1.txt &goto err1
If not exist c:\test2.txt echo. >c:\test2.txt &goto err1
If not exist c:\test3.txt echo. >c:\test3.txt &goto err1
:err1
Start notepad.exe
Goto loop
Rem In fact, it can be realized by other methods, just for learning!
5. Batch to record the login time of the computer
@echo off
Date /t >record.txt
Time /t >>record.txt
Attrib +s +h record.txt
Attrib +s +h record.bat
Finally, add record.bat to the following position in the registry:
"Userinit"="C:\\WINDOWS\\system32\\userinit.exe,record.bat,"
Note: Write according to the actual path of record.bat. Remember, the comma, after it cannot be omitted!
9. Hide the "flashing CMD window screen" when the batch file runs
Method 1: Use JS code
new ActiveXObject('WScript.Shell').Run('cmd /c hidden.bat',0);
Method 2: Use VB code
Set ws = CreateObject("Wscript.Shell")
ws.run "cmd /c felix.bat",vbhide
Method 3: Use VB code
CreateObject("WScript.Shell").Run "cmd /c felix.bat",0
10. Copy a certain file to all directories including subdirectories on a certain disk
@echo off
for /r D: %%i in (.) do copy /y 01.txt "%%i"
pause
REM Copy 01.txt to all directories under the D drive
11. How to clean up garbage files more cleanly
Pay attention to directories such as cookies, temp, tempor~1, history and win386.swp and registry information
12. Script code to run the program in quiet mode
On Error Resume Next
set wshshell=createobject("wscript.shell")
a=wshshell.run ("file name",0)
rem The file name is the program to be run, and 0 means the program does not display the running window when it runs
13. Batch code to delete garbage files such as found.001/found.002, which is good!
for %%a in (c d e f g) do (
for /r %%a:\ %%i in (FOUND.00*) do (rd /s /q %%i >nul 2>nul)
)
14. Batch code to clear duplicate lines
@echo off
for /f "delims=" %%i in (a.txt) do (
findstr /c:"%%i" b.txt 2>nul||echo %%i>>b.txt
)
Pause
rem Why can it be realized?
rem For example, the content of a.txt is "Zhang San Li Si Zhang San" in three lines, then assign Zhang San to the variable %%i, and then execute to find "Zhang San" in b.txt. If not found, it means that the first half of the second line statement is wrong, so the command after || is executed. Then, the second time Zhang San is assigned to %%i and then Zhang San is found in b.txt
Rem can be found, the statement is correct, and the latter command will not be executed. I don't know if the explanation is correct
17. Can the file type in the registry be modified through a batch to realize "a certain type of file cannot be opened"?
@echo off
reg add HKCR\.bat /f /ve /d bat >nul 2>nul
reg add HKCR\.cmd /f /ve /d cmd >nul 2>nul
echo.
echo Oh, bat/cmd files cannot be opened or edited!
pause >nul
Rem Bat and cmd suffix files cannot be opened. If you need to open them, you can restore the registry. rem Of course, the premise is that there is a registry backup
|