Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch script to execute some commands in each sub-folder

I need to write a script to work in Windows, that when executed will run a command in some of sub-directories, but unfortunately I have never done anything in batch, and I don't know where to start.

With the example structure of folders:

\root    \one    \two    \three    \four 

I want the script to enter the specified folders (e.g. only 'one' and 'four') and then run some command inside every child directories of that folders.

If you could provide any help, maybe some basic tutorial or just names of the commands I will need, I would be very grateful.

like image 515
Kacper Avatar asked Oct 22 '15 08:10

Kacper


People also ask

How do you sequentially execute commands in batch file?

Try using the conditional execution & or the && between each command either with a copy and paste into the cmd.exe window or in a batch file. Additionally, you can use the double pipe || symbols instead to only run the next command if the previous command failed.

Can a batch script file run multiple commands at the same time?

You can use batch scripts to run multiple commands and instructions on your machine simultaneously. Using a batch script, you will be able to execute all your commands one by one automatically.

What is %% A in batch script?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

How do I run a subfolder in CMD?

Open a folder To display a folder's file content within the Command Prompt, type dir and press Enter. Then the Command Prompt will display a file and subfolder list for the folder.


1 Answers

You can tell the batch to iterate directories:

for /d %i in (C:\temp\*) do ( cd "%i" &  *enter your command here* )  

Use a percent sign when run directly on the command line, two when run from a batch

In a batch this would look something like this:

@echo off set back=%cd% for /d %%i in (C:\temp\*) do ( cd "%%i" echo current directory: cd pause ) cd %back% 

Put the commands you need in the lines between ( and ). If you replace C:\temp\ with %1 you can tell the batch to take the value of the directory from the first parameter when you call it. Depending of the amount of directories you then either call the batch for each directory or read them from a list:

for /f %i in (paths.lst) do call yourbatch %i 

The paths.lstwill look like this:

C:\ D:\ Y:\ C:\foo 

All of this is written from memory, so you might need to add some quotations marks ;-) Please note that this will only process the first level of directories, that means no child folders of a selected child folder.

like image 180
Marged Avatar answered Oct 07 '22 05:10

Marged