Ginsor
Ginsor

Reputation: 149

Windows batch file with loop through subfolders

I didnt succeed writing an approriate batch file and would appreciate some help.

Let's say I have an exe in D:\Test\ called script.exe. To execute this script.exe it requires an additional argument of a .bin files (e.g. bin01.bin, bin02.bin).

Therefore it would be like: script.exe -i bin01.bin, script.exe -i bin01

I want the script to execute with all .bin files from all subfolders

D:\Test\script.exe
D:\Test\Folder01\bin01.bin
D:\Test\Folder01\bin02.bin
D:\Test\Folder02\bin01.bin
D:\Test\Folder03\bin01.bin

anyone could help me here? Thanks a lot in advance.

Upvotes: 4

Views: 23083

Answers (1)

Mofi
Mofi

Reputation: 49096

For direct execution from within a command prompt window:

for /R "D:\Test" %I in (*.bin) do @D:\Test\script.exe -i "%I"

And the same command line for usage in a batch file:

@for /R "D:\Test" %%I in (*.bin) do @D:\Test\script.exe -i "%%I"

The command FOR searches recursive in directory D:\Test and all subdirectories for files matching the wildcard pattern *.bin.

The name of each found file is assigned with full path to case-sensitive loop variable I.

FOR executes for each file the executable D:\Test\script.exe with first argument -i and second argument being the name of found file with full path enclosed in double quotes to work for any *.bin file name even those containing a space or one of these characters: &()[]{}^=;!'+,`~.

@ at beginning of entire FOR command line just tells Windows command interpreter cmd.exe not to echo the command line after preprocessing before execution to console window as by default.

@ at beginning of D:\Test\script.exe avoids the output of this command to console executed on each iteration of the loop.

Most often the echo of a command line before execution is turned off at beginning of the batch file with @echo off as it can be seen below.

@echo off
for /R "D:\Test" %%I in (*.bin) do D:\Test\script.exe -i "%%I"

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • echo /?
  • for /?

Upvotes: 10

Related Questions