如何递归执行 Windows 批处理命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2043869/
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 13:43:54  来源:igfitidea点击:

How to execute a windows batch command recursively?

windowsshellcommand-linebatch-filecmd

提问by Bassel Alkhateeb

For example, you have a rename command in a batch file, and you want to execute that file on the current directory and all sub-directories.

例如,您在批处理文件中有一个重命名命令,并且您想在当前目录和所有子目录上执行该文件。

回答by Joey

Suppose your batch is named something like myrename.cmd, then you can easily do the following:

假设您的批次名称类似于myrename.cmd,那么您可以轻松地执行以下操作:

call myrename.cmd
for /r /d %%x in (*) do (
    pushd "%%x"
    call myrename.cmd
    popd
)

The first line will run it for the current directory, the forloop will iterate recursively (/r) over all directories (/d) and execute the part in the parentheses. What we do inside them is change the directory to the one we're currently iterating over with pushd—which has the nice property that you can undo that directory change with popd—and then run the command, which then will be run in the directory we just switched to.

第一行将针对当前目录运行它,for循环将递归 ( /r)遍历所有目录 ( /d) 并执行括号中的部分。我们在其中所做的是将目录更改为我们当前正在迭代的目录pushd——它有一个很好的属性,你可以用它来撤消该目录更改popd——然后运行命令,该命令将在我们刚刚的目录中运行切换到。

This assumes that the batch lies somewhere in the path. If it doesn't and just happens to lie where the batch file above lies, then you can use

这假设批次位于路径中的某处。如果它没有并且恰好位于上面的批处理文件所在的位置,那么您可以使用

"%~dp0myrename.cmd"