Page 1 of 1

Can this be done with a FOR loop?

Posted: 2023-Jan-12, 11:14 pm
by GeoffL
The following is an amateurish attempt at a looping routine. The intent is to be able to easily modify the source directory list and not have to manually modify multiple instances of the processes to be performed (each of which may contain multiple instances of the directory name). Note that the directories (or paths) in the list do not share a common parent directory and may be scattered all about local and network drives.

It would seem that this is a perfect candidate for a more elegant FOR loop (with which I have no experience – neither FOR statements nor elegant code!). Is it feasible and, if so, what would the code be to accomplish it?

Example code:


@echo off

set _NbrOfSources=0

set _Source_1=Directory_1 && set /a _NbrOfSources=%_NbrOfSources% + 1
set _Source_2=Directory_2 && set /a _NbrOfSources=%_NbrOfSources% + 1
set _Source_3=Directory_3 && set /a _NbrOfSources=%_NbrOfSources% + 1
rem *
rem *
rem *
rem set _Source_nn=<directory name> && set /a _NbrOfSources=%_NbrOfSources% + 1

set _Count=1

:LOOP1

set _Source=_Source_%_Count%

call set _Iteration=%%%_Source%%%

echo Do a series of things here, utilizing the directory name held in the variable %%_Iteration%%,
echo.
echo where the value of %%_Iteration%% is currently: %_Iteration%
echo.
echo.
echo.

pause

echo.
echo.
echo.

set /a _Count=%_Count%+1

if %_Count% GTR %_NbrOfSources% echo Completed Loop && goto end

GOTO LOOP1

:end
echo.
echo.
pause

Re: Can this be done with a FOR loop?

Posted: 2023-Jan-16, 9:05 am
by bluesxman
You're probably looking for something like this:

Code: Select all

@echo off
REM location of a text file containing the list of directories
set "dirlist=D:\Some Directory\dirlist.txt"

for /f "usebackq tokens=*" %%a in ("%dirlist%") do (
  call :subroutine "%%~a"
)
goto :EOF

:subroutine
echo:Do something with "%~1" here
goto :EOF