Batch File folder detection

时间:2015-10-30 22:27:08

标签: windows batch-file cmd

Yes, I know I need to double-up the %a to be %%a when used in a batch file. ;)

This works, but does not give me the results I want - this is just too much..

FOR /f %a IN ('dir "D:\tomcat*" /ad /b ')  DO FOR /f %b IN ('dir "D:\%a\webapps" /ad /b ') DO ECHO D:\%a\webapps\%b

What I would really like to do is:

FOR /f %a IN ('dir "D:\tomcat*\webapps" /ad /b ')  DO ECHO %a

But, I get the resulting error:

The filename, directory name, or volume label syntax is incorrect.

I would like to do this as I have a need to detect which folders have tomcat in them and could be any of the following:

D:\tomcat
D:\tomcat1
D:\tomcat2
D:\tomcat_1
etc.

Thanks!

2 个答案:

答案 0 :(得分:3)

you could use IF EXIST

FOR /f %a IN ('dir "D:\tomcat*" /ad /b ')  DO IF EXIST "%~a\webapps\nul" dir /b "%~a\webapps"

\nul is to check if folder exist.

答案 1 :(得分:3)

通配符(?*)只能在路径的 last 项中使用,因此您必须解决此问题。

作为您正在使用的嵌套for循环的替代方法,您还可以执行以下操作:

for /F "eol=| delims=" %A in ('dir /A:D /B "D:\tomcat*"') do (> nul 2>&1 dir /A:D "%~A\webapps" && echo "%~A")

这将输出名称中包含tomcat的所有文件夹,其名称​​和都有一个名为webapps的子目录。

您需要为"eol=| delims="提供选项字符串for /F;这也适用于具有两个嵌套for循环的变体。