如何使用for循环遍历目录中的每个文件?
我如何判断某个条目是一个目录还是一个文件?
如何使用for循环遍历目录中的每个文件?
我如何判断某个条目是一个目录还是一个文件?
当前回答
在我的情况下,我必须删除临时文件夹下的所有文件和文件夹。这就是我最后做这件事的原因。我必须运行两个循环一个文件和一个文件夹。如果文件或文件夹名称中有空格,则必须使用" "
cd %USERPROFILE%\AppData\Local\Temp\
rem files only
for /r %%a in (*) do (
echo deleting file "%%a" ...
if exist "%%a" del /s /q "%%a"
)
rem folders only
for /D %%a in (*) do (
echo deleting folder "%%a" ...
if exist "%%a" rmdir /s /q "%%a"
)
其他回答
这将递归地列出当前目录及其子目录中的所有文件(仅是文件):
for /r %i in (*) do echo %i
此外,如果在批处理文件中运行该命令,则需要将%符号加倍。
for /r %%i in (*) do echo %%i
(感谢@agnul)
试试这个:
::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 ..)
从命令行运行FOR和从批处理文件运行FOR之间有细微的区别。在批处理文件中,您需要在每个变量引用前放置两个%字符。
从命令行:
FOR %i IN (*) DO ECHO %i
从批处理文件:
FOR %%i IN (*) DO ECHO %%i
在我的情况下,我必须删除临时文件夹下的所有文件和文件夹。这就是我最后做这件事的原因。我必须运行两个循环一个文件和一个文件夹。如果文件或文件夹名称中有空格,则必须使用" "
cd %USERPROFILE%\AppData\Local\Temp\
rem files only
for /r %%a in (*) do (
echo deleting file "%%a" ...
if exist "%%a" del /s /q "%%a"
)
rem folders only
for /D %%a in (*) do (
echo deleting folder "%%a" ...
if exist "%%a" rmdir /s /q "%%a"
)
它也可以使用forfiles命令:
forfiles /s
还要检查它是否是一个目录
forfiles /p c:\ /s /m *.* /c "cmd /c if @isdir==true echo @file is a directory"