Reputation: 449
I have a parent folder containing several child folders. I am trying to run a bat script that runs a specific operation under the child folders. But, I do not want the script to run in all of the child folders. I need to exclude a few from the list. This is what I have now:
pushd
for /D %%i in (<<path To Parent>>\*) do call :$myFunc "%%i"
popd
exit /B
:$myFunc
for %%g in ("Child2"
"Child3") do ( if /I "%1"=="%%~g" goto match )
echo current directory: %1
exit /B
:$match
echo matched directory
exit /B
In the :$myFunc
subroutine, I can do a cd %1
to enter that child directory and run my command then do a cd
to come back to the parent folder. One thing I am trying to do before is to exclude the :$myFunc
operation if the incoming folder is on my exclude list.
Folder tree:
ParentFolder
Child1
Child2
Child3
Child4
Given a sample folder structure like above, how can I not call myFunc
when the for selects Child2
and Child3
.
Any suggestions on how I can achieve this?
Upvotes: 1
Views: 98
Reputation: 5519
That's certainly possible and can be done with the following code (lots of changes):
@echo off
setlocal EnableDelayedExpansion
rem Set which folders to exclude. This is changeable and NOT HARDCODED:
set exclude_folders="Child2" "Child3"
for /F %%A IN ('dir /B /AD "<path to parent>"') do (
if "!exclude_folders:%%~nxA=!" == "%exclude_folders%" (call :$myFunc "%%A" "%%~fA")
)
exit /b %errorlevel%
:$myFunc
pushd "%~2"
rem Do your commands here; don't use pushd again!
popd
Note that the first argument is the folder name if it is located it in %cd%
. Else, it is full path. The second argument is optional and more general, but I am sure you will need it!
I have changed the code as follows:
exclude_folders
to list here the folders you want to execute.for /F
loop to loop through a command, (dir /B /AD
) to loop through all folders, avoid hidden ones!%%~nxA
) [used %%~nxA
because folder may contain a dot (.
)] is excluded from the exclude_folders
and the variable changes (in other words if string foldername
exists in exclude_folders
) this means that the folder is blacklisted and the for
loop will start with the next line, since there is no command for else
. If the opposite happens, call
subroutine $myFunc
with two arguments: %%A
and %%~fA
%~2
folder and return back to the loop.exit
.Upvotes: 2