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.
Asked
Active
Viewed 1.4k times
10

Bill the Lizard
- 398,270
- 210
- 566
- 880

Bassel Alkhateeb
- 1,584
- 5
- 19
- 35
-
do you have a concrete example? – Rubens Farias Jan 11 '10 at 18:31
-
See also: http://stackoverflow.com/a/25381530/99777 – joeytwiddle Jun 06 '16 at 01:34
-
Possible duplicate of [Windows Batch File Looping Through Directories to Process Files?](https://stackoverflow.com/questions/8397674/windows-batch-file-looping-through-directories-to-process-files) – Robert Pollak Sep 25 '18 at 07:39
1 Answers
17
Suppose your batch is named something like myrename.cmd
, then you can easily do the following:
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 for
loop 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.
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"
-
-
@VirgilIerubino: What last bit? The part with `%~dp0`? See `help for` for an explanation. – Joey Mar 01 '17 at 17:45