0

I've been trying to use MOD (%%) in order to make a timeout /t 3 command every 25 loops I am getting an error "invalid operand" Code is:

set /a var1=0
FOR /R "folder" %%G in (.) DO (
 Pushd %%G
set /a b=%%var1%% %% 25
 IF %%b%% EQU 0 (
    timeout /t 3
  )
 set /a var1=%%var1%%+1
 Popd
)
Nisan Bahar
  • 73
  • 1
  • 1
  • 8

2 Answers2

2

aschipfl has identified the problem and provided a fix. But there is a very concise and efficient way to accomplish your goal without any delayed expansion using only a single SET /A statement.

You can combine multiple computations and assignments within one SET /A. You can even use the result of an assignment expression within an even larger expression.

You can avoid an IF statement by intentionally dividing by zero. When the modulo result is 0, the division fails, and any error messages are hidden by redirecting stderr to nul. The conditional || command concatenation operator only fires if the preceding command failed, in this case when dividing by 0.

I don't understand the purpose of your loop - it seems pointless. But the correct pause is introduced with the following:

set /a var1=0
for /r "folder" %%G in (.) do (
  pushd "%%~G"
  set /a "1/((var1+=1) %% 25)" 2>nul || timeout /t 3
  popd
)
Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390
1

Why are you enclosing variable names in pairs of % signs? The usual syntax for reading a variable is %var1%.

set /A can read variables even without percent signs around, so use set /a b=var1 %% 25.
The other set /A command line can be changed to set /A var1+=1.

There is one problematic variable in your code, namely b, because you are writing and reading it within the same (parenthesised) block of code, so %b% is read when the entire for loop is parsed, at which point it is empty most probably.
For such cases, you need to apply delayed expansion, so the variable is read at execution time. To enable it, use the setlocal command; to actually use it, write !b! instead of %b%.

Here is the fixed code:

set /A var1=0
for /R "folder" %%G in (.) do (
    pushd "%%~G"
    set /A b=var1 %% 25
    setlocal EnableDelayedExpansion
    if !b! EQU 0 (
        timeout /T 3
    )
    endlocal
    set /A var1+=1
    popd
)

Here I placed setlocal and endlocal inside the loop so that delayed expansion is disabled during expansion (reading) of the for loop variable %%G, because in case it contains exclamation marks, they would get lost otherwise.

aschipfl
  • 33,626
  • 12
  • 54
  • 99