Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have a folder with files having .foo extension.

I need a batch file to execute some commands for each file in that folder having that extension.

How should i do that?

Seems I need a loop after getting the file list but I don't know how to do this in batch files... (I'm on Windows Xp but I guess the answer would be valid on other Windows).

share|improve this question

2 Answers 2

up vote 4 down vote accepted
FOR %%F in (*.foo) DO command %%F

Operates the command command on with each filename as the first argument.

Remember that when in a batch file you must use %% where on the command line, the above would only use single %'s.

If you need the full pathname, or to get files recursively, use the /R switch of the for command.

Example:

C:\WINDOWS> FOR %F in (*.exe) DO @echo %F

explorer.exe
FramePkg.exe
gsk7bui.exe
hh.exe
IsUninst.exe
NOTEPAD.EXE
notepad1.exe
regedit.exe
slrundll.exe
TASKMAN.EXE
twunk_16.exe
twunk_32.exe
uninst.exe
winhelp.exe
winhlp32.exe

C:\WINDOWS> FOR /R %F in (*.exe) DO @echo %F

C:\WINDOWS\explorer.exe
C:\WINDOWS\FramePkg.exe
C:\WINDOWS\gsk7bui.exe
C:\WINDOWS\hh.exe
C:\WINDOWS\IsUninst.exe
C:\WINDOWS\NOTEPAD.EXE
C:\WINDOWS\notepad1.exe
C:\WINDOWS\regedit.exe
C:\WINDOWS\slrundll.exe
C:\WINDOWS\TASKMAN.EXE
C:\WINDOWS\twunk_16.exe
C:\WINDOWS\twunk_32.exe
C:\WINDOWS\uninst.exe
C:\WINDOWS\winhelp.exe
C:\WINDOWS\winhlp32.exe
... [lots more] ...
C:\WINDOWS\system32\accwiz.exe
C:\WINDOWS\system32\actmovie.exe
C:\WINDOWS\system32\ahui.exe
C:\WINDOWS\system32\alg.exe
C:\WINDOWS\system32\append.exe
C:\WINDOWS\system32\arp.exe
C:\WINDOWS\system32\asr_fmt.exe
C:\WINDOWS\system32\asr_ldm.exe
... [etc..]
C:\WINDOWS\system32\dllcache\accwiz.exe
C:\WINDOWS\system32\dllcache\actmovie.exe
C:\WINDOWS\system32\dllcache\admin.exe
C:\WINDOWS\system32\dllcache\agentsvr.exe
C:\WINDOWS\system32\dllcache\ahui.exe
C:\WINDOWS\system32\dllcache\alg.exe
C:\WINDOWS\system32\dllcache\append.exe
C:\WINDOWS\system32\dllcache\arp.exe
... [and so forth..]

share|improve this answer

You can use the FOR loop to perform an action on each file

FOR %%parameter IN (set) DO command

Like

FOR %%G in ("C:\*") DO echo %%G
share|improve this answer
    
I should then replace the "C:*" part by "myfolder*.foo", right? –  Klaim Aug 4 '09 at 16:58
    
Correct. If there are spaces in the path, I believe you have to use ^ in front of them as an escape character –  Kevin Kuphal Aug 4 '09 at 17:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.