Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a project folder with a great number of projects inside. Is there a way I can create a bat file which goes into each of these project folders and runs a couple of commands?

What I would like is to automate what I now would do manually:

> cd dir1
> command1 arg1 arg2
> command2 arg1 arg2
> cd ..
> cd dir2
> ...

Is this possible to automate with a bat file?

share|improve this question

3 Answers 3

Tried to use what I found in a forum thread. Seems to work?

pushd C:\projects
for /f "Delims=" %%i in ('dir /ad /b') do (
    cd "%%i"
    command1 arg1 arg2
    command2 arg1 arg2
    cd ..
)
popd

Not sure I get the /f "Delims= part for example though... I'd also like to exclude some directories. Please comment if you know how :)

share|improve this answer
    
A basic method, would be for you to have a file with only the directories you want. Use dir /ad/b to help build the file. dir /ad/b >dirlist Then use for /f, with the filename, to run commands on each line of the file. e.g. if your file is called dirlist, then use for /f %f in (dirlist) do (and then the rest). i'm not sure about the brackets for the body of the for loop and the multi-line aspect, but anyway. –  barlop Apr 29 '11 at 21:01
1  
"delims=" is necessary to do not use delimiters. default delimiter is space character, so if a folder have some space in its name some problems will occurr (like if one directory is "c:\documents and settings\user"; without "delims=", the first delimiter will be the first space after "documents" and the batch will try to access "c:\documents" instead). –  kokbira Jun 13 '11 at 20:01
    
+1 for pushd/popd :) –  kokbira Jun 13 '11 at 20:01

You can use all the commands from the command line in BAT file, so I'm not sure what your question is.

Just write a BAT file like this:

cd dir1
command1 arg1 arg2
command2 arg1 arg2
cd ..
cd dir2

If you have many directories and the commands are always the same, put them in a second BAT script and use a for loop:

for %%a IN ('dir /b %PROJECT_FOLDER%') do call second_script.bat %%a

Check the help for dir if you have files and directories in %PROJECT_FOLDER%. There should be an option to list only directories.

share|improve this answer
pushd C:\projects
:: your 'for /f' was correct, but unnecessary
for /d %%i in (*) do call :foo "%%~i"
popd
goto :eof

:foo
    if "%~1"=="junk" goto :eof
    if "%~1"=="unneeded directory" goto :eof

    pushd "%~1"
    command1
    command2
    popd
    goto :eof

Alternatively, if you only want to include a few specific directories:

for /d %%i in (a b c) do ...
share|improve this answer

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.