Dos FOR loop question

Here is my batch file.

For /f %%a IN (‘R:\ /b *.mdb’) do call "C:\Program Files\Microsoft Office\Office14\msaccess.exe" %%a /compact

I am trying to run through the R drive and grab all the .mdb's and do compact from msaccess but when I run this through command prompt I get this error:

%%a was unexpected at this time

Any suggestions on how to get this For loop command to work properly.
Who is Participating?
Steve KnightConnect With a Mentor IT ConsultancyCommented:
You could have a list of entries to exclude in a text file perhaps, e.g.


then use a find /v command as part of the dir command to exclude those lines, they would only need to be a partial match (but not wildcards), e.g. if you want to exclude a whole subdir worth then include that path in the file

@echo off
set exclude="r:\exclude.txt"
FOR /F "delims=*" %%a IN ('DIR /b /s R:\*.mdb ^|findstr /i /v /g:%exclude%') do call "C:\Program Files\Microsoft Office\Office14\msaccess.exe" "%%a" /compact

That says to take the dir listing of all MDB files in the R: drive and all subdirs then pass that to findstr to find all lines that do NOT match any of the search strings in the r:\exclude.txt file.

Lee W, MVPTechnology and Business Process AdvisorCommented:
you cut and paste, didn't you?  


You have:
For /f %%a IN (‘R:\ /b *.mdb’) do call "C:\Program Files\Microsoft Office\Office14\msaccess.exe" %%a /compact
For /f %%a IN ('R:\ /b *.mdb') do call "C:\Program Files\Microsoft Office\Office14\msaccess.exe" %%a /compact

(Note the TYPE of quote surrounding R:\ /b *.mdb)
The new generation of project management tools

With’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

goretailproAuthor Commented:
I did but I still get the same message...
I think he means:

  IN ('dir/s/b R:\*.mdb')
... and if any of your .mdb files have spaces in the name, put quotes here:  "%%a" /compact
Steve KnightIT ConsultancyCommented:
Oh and the obvious... if you are typing that at the command line use %a instead of %%a (which is for batch files).

Farhan KaziConnect With a Mentor Systems EngineerCommented:
Are you executing above statement from command line? if yes then you need to remove one % sign from FOR statement.

FOR /F "delims=*" %a IN ('DIR /b /s R:\*.mdb') do call "C:\Program Files\Microsoft Office\Office14\msaccess.exe" "%a" /compact

in batch file, following should work:

FOR /F "delims=*" %%a IN ('DIR /b /s R:\*.mdb') do call "C:\Program Files\Microsoft Office\Office14\msaccess.exe" "%%a" /compact

Hope this helps!
Farhan KaziSystems EngineerCommented:
Sorry Steve, didn't refresh the page :(
goretailproAuthor Commented:
Is there a way to exclude specific MDB's?
All Courses

From novice to tech pro — start learning today.