August 25, 2009

The Power of DOS: Looping Through Subfolders

Filed under: Automation,Scripting — Marcus Tettmar @ 7:37 pm

Twice today, for two different people, I needed to write some code to iterate through files in a tree of subfolders. The subfolder structure could not be known up front and there may be any number of subfolders and any number of folders deep.

One could use GetDirList iteratively, or use VBScript’s FileSystem Object. But then I was reminded of the power of DOS by JRL in this post.

The following returns a file containing a list of the jpg files throughout all folders, starting in c:\root_folder\ with full paths:

dir c:\root_folder\*.jpg /s /b > outputfile.txt

So, as JRL suggests, we can call that command from Macro Scheduler and then read in the output file. We should use a temporary file:

Let>RP_WINDOWMODE=2
Let>RP_WAIT=1
Run>cmd /c dir c:\root_folder\*.jpg /s /b > %TEMP_DIR%~temp_dir_list~
ReadFile>%TEMP_DIR%~temp_dir_list~,dir_list

Now we can explode that list into an array and loop through it, doing whatever it is we need to do to each file:

Separate>dir_list,CRLF,files
If>files_count>0
Let>f=0
Repeat>f
  Let>f=f+1
  Let>this_file=files_%f%
  //do something with this_file
Until>f=files_count

It’s easy to forget the power of DOS – it can save you a fair few lines of code sometimes.

Remember that any DOS command can be “piped” to an output file by appending >filename to the command line. This is very useful as we can then use ReadFile to get the output from the command, as we have done above.