上面章节中介绍了 for 语句基础语法以及 for /D 扩展的用法。
本章节将介绍 for /R 扩展的用法。/R 语法如下:
FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]将递归进入根目录树 [Drive:]Path,在树的每个目录中执行 for 语句。如果在 /R 后没有指定目录,则认为是当前目录。如果 set 只是一个句点(.),则只枚举目录树。
实例:搜索当前目录下的所有文件。
@echo off
for /r %%i in (*) do echo %%i
pause输出结果:
C:\Users\Administrator\Desktop\bat> test.bat
"C:\Users\Administrator\Desktop\bat\call.bat"
"C:\Users\Administrator\Desktop\bat\for.txt"
"C:\Users\Administrator\Desktop\bat\hello.bat"
"C:\Users\Administrator\Desktop\bat\test.bat"
"C:\Users\Administrator\Desktop\bat\tmp\for.txt"
"C:\Users\Administrator\Desktop\bat\tmp\ipconfig.txt"
"C:\Users\Administrator\Desktop\bat\tmp\ping.txt"
"C:\Users\Administrator\Desktop\bat\tmp\for\for.txt"
"C:\Users\Administrator\Desktop\bat\tmp\for\if.txt"
请按任意键继续. . .运行结果将显示,当前目录下的所有文件以及该目录下所有子目录里的所有文件。
实例:输出 D 盘下面所有的目录
@echo off
for /r d:/ %%i in (.) do echo %%i
pause输出结果:
C:\Users\Administrator\Desktop\bat> test.bat
d:\.
d:\360Downloads\.
d:\360Downloads\Software\.
d:\360Downloads\Software\漏洞补丁目录\.
d:\360Downloads\Software\漏洞补丁目录\sxs\.
d:\360Downloads\wpcache\.
d:\360Downloads\wpcache\srvsetwp\.
d:\360Rec\.
d:\Config.Msi\.
d:\developerDoc\.
d:\developerDoc\文档\.
d:\developerLibs\.
... 省略 ...实例:搜索C盘里所有的扩展名为exe的文件。
@echo off
for /r c:/ %%i in (*.exe) do echo %%i
pause输出结果:
C:\Users\Administrator\Desktop\bat> test.bat
c:\AMD\WU-CCC2\ccc2_install\WULaunchApp.exe
c:\AMD\WU-CCC2\ccc2_install\Support64\CCC2App64.exe
c:\AMD\WU-CCC2\ccc2_install\VC12RTx64\vcredist_x64.exe
c:\AMD\WU-CCC2\ccc2_install\VC12RTx86\vcredist_x86.exe
c:\AMD\WU-CCC2\ccc2_install\VC13RTx64\vcredist_x64.exe
... 省略 ...运行结果将显示C盘和C盘里各个文件夹下的exe文件。
实例:搜索 C 盘是否有 notepad.exe 可执行文件。如果存在,则使用 start 启动 notepad.exe 程序。
@echo off
for /r c:/ %%i in (notepad.exe) do (
if exist %%i (
echo 找到了 notepad.exe
REM 去启动 notepad.exe
start %%i
goto end
)
)
echo 没有找到 notepad.exe
:end输出结果:
C:\Users\Administrator\Desktop\bat> test.bat
找到了 notepad.exe