troubleshooting Question

How to increment counter variable in "DOS" batch file

Avatar of Sharp2b
Sharp2bFlag for Sweden asked on
Microsoft DOSWindows XP
4 Comments1 Solution109547 ViewsLast Modified:
I try to create a batch file to run under Windos XP in a command window (or just double clicking the BAT file).

The intention is to take all files with a given extension, concatenate them and add some extra information "between the files". To do this, I need to add a counter value like 1 for the first file, 2 for the second and so on. I have managed to solve all other problems to output what I need but the counter variable is not updated as long as I'm inside the FOR loop. See the attached code example. Put it in a BAT file and run it to see the problem. The last echo after the FOR loop gives the correct value.

Any hints are much appreciated.
@echo off
 
set /A Counter=1
 
echo Initial value of Counter: %Counter%
echo.
 
for %%f in (*.*) do (
	echo File found: %%f
	echo Counter Before increment: %Counter%
	set /A Counter+=1
	echo Counter After Increment: %Counter%
	echo.
)
 
echo Counter after for loop: %Counter%
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 4 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros