如何在 Windows Shell 中迭代一组文件夹?

发布于 2024-10-06 02:45:25 字数 500 浏览 4 评论 0原文

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

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

输出:

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

我做错了什么?如何更改该脚本,以便它迭代该一个文件夹,并且一旦发现没有名为“Subfolder”的子文件夹,它就会创建该子文件夹?还有关于编写此类脚本的好教程吗?

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:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧城空念 2024-10-13 02:45:26

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

因此,如果您想列出 C: 的所有目录,您应该这样做:

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

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

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

这将遍历所有 Windows 子目录查找 JPG。瞧你应该能够做到 /d /r 并且此参考建议你可以 -我根本做不到,但也许你能做到这一点?

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

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

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

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

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

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

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

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

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

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

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

Note that dir is used in conjunction with /ad/s/b which 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

空袭的梦i 2024-10-13 02:45:26

这对我有用:

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

This works for me:

echo %ROOT%
for /D %%f in (%ROOT%\Binaries\*) do echo %%f && if not exist %%f\Subfolder md %%f\Subfolder
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文