1

I want to have a loop in a batch file and in every execution i want to count the number of the files in a folder. The problem is that the counter in fisrt execution is always unknown and makes the script unusable.

loop:
@set /a counter=%counter%+1 
@if %counter% GTR 2 (
@set file_counter=0
for %%x in ("%Stckalz_Input%\%Directory_Stckalz_Job%\Results\*") do (set /a file_counter+=1)
@echo Server is busy or not responding. %file_counter%
)
goto loop

The concept is to wait for some loops until the program is ended. When the Results folder is empty then the user has an error. The issue is that at the first execution the file_counter variable is always not declared. Could someone help me ?

xmaze
  • 13

1 Answers1

0

The problem is the if statement block - it is evaluated in one chunk. Solve with two changes:

  1. add setlocal delayedexpansion
  2. use !variable! inside blocks instead of %variable% to have them evaluated "on the fly".

You can see a good explanation at: this super user answer by Joey

Your code should look like:

setlocal enabledelayedexpansion

:loop
@set /a counter=%counter%+1 
@if %counter% GTR 2 (
   @set /a file_counter=0
   for %%x in ("%Stckalz_Input%\%Directory_Stckalz_Job%\Results\*") do (set /a file_counter+=1)
   @echo Server is busy or not responding. !file_counter!
)
goto :loop
Scott
  • 28
  • 3