【问题标题】:Loop through folder tree and execute bat file in subfolders in parallel(accessing the files in the subfolder)遍历文件夹树并并行执行子文件夹中的bat文件(访问子文件夹中的文件)
【发布时间】:2014-05-11 19:34:45
【问题描述】:

我试图在父文件夹folder1 中有一个bat 文件,这个名为run.bat 的bat 文件将遍历所有子文件夹,并同时调用一个名为child.bat 的bat 文件,但是,这些child.bat 将不得不访问同一文件夹中的其他文件。

例如:

Folder1 (have run.bat)
  |
  |_______Folder2
  |           |
  |           |_______aa.txt
  |           |
  |           |_______child.bat
  |
  |_______Folder3
            |
            |_______bb.txt
            |
            |_______child.bat

Folder2中的child.bat,内容为:

type aa.txt

Folder3中的child.bat,内容为:

type bb.txt

我知道关于如何遍历子文件夹以及在子文件夹中运行 bat 文件的问题已经存在。但我的问题是,bat 文件必须访问位于同一子文件夹中的其他文件。如果我们不输入子文件夹(cd subfolder),child.bat 将不会成功执行。这是我尝试过的run.bat的内容:

@echo off
for /d /r %%i in (*) do ( 
   cd %%i
   start "%%i\child.bat"
  )

但是,失败了。

有什么想法吗?

【问题讨论】:

    标签: loops batch-file


    【解决方案1】:

    我的猜测是脚本必须能够从调用for 循环的同一位置一致地更改目录。只需保存当前文件夹(通过pushd)并在子调用后恢复它(通过popd)就足够了。

    @echo off
    FOR /d /r %%i IN (*) DO (
       pushd "%%i"
       call "child.bat"
       popd
    )
    

    【讨论】:

    • if exist "child.bat" call "child.bat"
    • 谢谢你们。我不得不说,它有效。但实际上在我的情况下,我必须并行调用 child.bat。这就是我使用“开始”的原因。如果我使用开始,它就不起作用。 @echo off FOR /d /r %%i IN (*) DO ( pushd "%%i" start "child.bat" popd )
    【解决方案2】:

    根据您在 cmets 中的额外信息,这应该适合您。

    @echo off
    FOR /d /r %%i IN (*) DO (
       if exist "%%i\child.bat" start "" /d "%%i" "%comspec%" /c "child.bat"
    )
    

    【讨论】:

    • 谢谢你 foxidrive。但是弹出的cmd窗口很快就消失了。我在新的 cmd 窗口中看不到 child.bat 的结果。
    • 你能描述一下它是如何失败的吗?我很好奇为什么它不起作用。
    • 好吧。当我运行你的脚本时,只是看到窗口弹出,很快就消失了。同时cmd主窗口也没有显示任何结果。
    • 如果我将 pushd 和 popd 添加到您的脚本中,像这样 @echo off FOR /d /r %%i IN (*) DO ( pushd "%%i" if exist "%%i\child.bat" start "" /d "%%i" "%comspec%" /c "child.bat" popd ) 再次失败。
    • 它不需要pushd/popd,因为start 命令包含该功能。将pause 作为最后一行并尝试一下。如果您更改 child.bat,请确保在两个位置都正确拼写。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 2014-09-28
    • 2018-12-20
    • 2023-01-20
    • 2017-02-08
    相关资源
    最近更新 更多