如何遍历 Windows Shell 中的一组文件夹?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4375890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:44:47  来源:igfitidea点击:

How do I iterate over a set of folders in Windows Shell?

windowsshellscriptingcmd

提问by sharptooth

I'm currently trying to write a .cmd Windows Shell script that would iterate over a set of folders. However even the following simplest script:

我目前正在尝试编写一个 .cmd Windows Shell 脚本来遍历一组文件夹。然而,即使是以下最简单的脚本:

echo "%ROOT%"
for %%f in ("%ROOT%\Binaries\" ) do (
    echo "%%f"
    if not exist "%%f\Subfolder"
        md "%%f\Subfolder"
)

outputs:

输出:

CurrentDir>echo "<ActualPathToRoot>"
"<ActualPathToRoot>"
%f\Subfolder was unexpected at this time
CurrentDir>if exists "%f\Subfolder"

What am I doing wrong? How do I alter that script so that it iterates over that one folder and once it see there's no subfolder named "Subfolder" it creates that subfolder? Also is there a good tutorial on writing such scripts?

我究竟做错了什么?我如何更改该脚本,以便它遍历那个文件夹,一旦它看到没有名为“子文件夹”的子文件夹,它就会创建该子文件夹?还有关于编写此类脚本的好教程吗?

采纳答案by detunized

This works for me:

这对我有用:

echo %ROOT%
for /D %%f in (%ROOT%\Binaries\*) do echo %%f && if not exist %%f\Subfolder md %%f\Subfolder

回答by Dennis G

For (sub)folder-iteration you need to use a different forparameter.

对于(子)文件夹迭代,您需要使用不同的for参数。

So if you want to list all directories of C:you should do this:

所以如果你想列出 C: 的所有目录,你应该这样做:

for /d %%A in (C:\*) do echo %%A

Note the parameter /dwhich indicates a directory. To go into subdirectories you need to do a recursive for with /r

请注意/d指示目录的参数。要进入子目录,您需要对 with 进行递归/r

for /r C:\Windows %%A in (*.jpg) do echo %%A

This would iterate through all Windows subdirectorieslooking for JPGs. Low behold you should be able to do /d /rand this reference suggestsyou can - I simply can't, but maybe you are able to do this?

这将遍历所有 Windows 子目录以查找 JPG。瞧,你应该能够做到/d /r这个参考资料表明你可以——我根本不能,但也许你能够做到这一点?

A workaround I quickly jotted down is to just do a dirof all directories in a for loop:

我快速记下的解决方法是只dir在 for 循环中执行所有目录中的一个:

for /f "delims=" %%A in ('dir /ad/s/b') do echo %%A

Note that diris used in conjunction with /ad/s/bwhich performs a recursive listing of directories, printing the names of the directories found.
With these tools in your hand you should be able to do your if-subfolder construct. Note that you might need

请注意,dir/ad/s/bwhich结合使用执行目录的递归列表,打印找到的目录的名称。
有了这些工具,您应该能够进行 if-subfolder 构造。请注意,您可能需要