如何使用for循环遍历目录中的每个文件?

我如何判断某个条目是一个目录还是一个文件?


当前回答

%1是传入的第一个参数,不能在迭代器中使用。

试试这个:

@echo off
for %%i in (*.*) do echo %%i

其他回答

这将递归地列出当前目录及其子目录中的所有文件(仅是文件):

for /r %i in (*) do echo %i

此外,如果在批处理文件中运行该命令,则需要将%符号加倍。

for /r %%i in (*) do echo %%i

(感谢@agnul)

下面的代码在当前目录中创建一个名为“AllFilesInCurrentDirectorylist.txt”的文件,其中包含当前目录中所有文件(仅为文件)的列表。看看吧

dir /b /a-d > AllFilesInCurrentDirectorylist.txt

%1是传入的第一个参数,不能在迭代器中使用。

试试这个:

@echo off
for %%i in (*.*) do echo %%i

试试这个:

::Example directory
set SetupDir=C:\Users

::Loop in the folder with "/r" to search in recursive folders, %%f being a loop ::variable 
for /r "%SetupDir%" %%f in (*.msi *.exe) do set /a counter+=1

echo there are %counter% files in your folder

它会计算目录(以及子目录)中的。msi和。exe文件。因此,作为可执行文件的文件夹和文件之间也有区别。

如果需要过滤循环中的其他文件,只需添加一个扩展名(.pptx .docx ..)

我很难让jop的答案与绝对路径一起工作,直到我发现这个参考:https://ss64.com/nt/for_r.html

下面的示例循环遍历一个由绝对路径给出的目录中的所有文件。

For /R C:\absoulte\path\ %%G IN (*.*) do (
  Echo %%G
)