【问题标题】:Check if a directory contains only subdirectories and no files检查目录是否仅包含子目录而没有文件
【发布时间】:2023-03-27 05:06:02
【问题描述】:
我有一个目录,其中包含如下子目录:
C:\FILES
C:\FILES\DONE
我想检查 FILES 是否包含文件:
if not exist C:\FILES\*.* (
echo No files to process.
exit /b
)
但是由于子目录,测试“不存在...”永远不会为真。
关于如何检查目录是否有任何不是目录的文件的任何想法?
【问题讨论】:
标签:
windows
batch-file
cmd
【解决方案1】:
尝试获取文件列表,如果失败则没有文件
dir /a-d "c:\files\*" >nul 2>nul || (
echo No files to process
exit /b
)
如果没有文件,dir /a-d 命令(开关表示排除目录)将失败。 || 是一个条件执行操作符,如果前一个命令失败,它将执行以下命令。
【解决方案2】:
只有当有文件时,for才会执行goto。
for %%a in (C:\FILES\*.*) do goto files
echo No files to process.
exit /b
【解决方案3】:
简单代码:
for /f "delims=|" %%f in ('dir /b c:\FILES\') do goto :files
echo No files found
pause
goto:eof
:files
echo Files found
pause
goto:eof
【解决方案4】:
如果要检查此级别是否存在子目录:
(DIR /D "C:\FILES\" | findstr /i /p /r /c:"2 Directory" > nul 2> nul) && echo "No directories except current and parent."
这个简单的内联命令可以很容易地适应任何情况;-)
【解决方案5】:
试试
if not exist dir c:\FILES\*.* /a:-d (
您可以在dir here找到更多信息
PS
我手头没有 DOS。所以无法测试上面的代码sn-p。但我认为它接近您正在寻找的东西。如果不是非常接近的东西应该可以工作。