-1

I was not sure which title is better, so I will put both of them here:

  • How to increase and reuse an external variable inside a for loop?
  • How to create a second counter inside a for loop?

Update:
The best title for this question is: Variable does not increase when inside a for loop. (Proberbly is duplicated)


I made this script to convert multi-line commands into single line:

@echo off
setlocal enabledelayedexpansion
set ln1=taskkill /f /fi "IMAGENAME eq RuntimeBORker*"
set ln2=taskkill /f /fi "IMAGENAME eq sCVhost*"
REM letters are fliped incase you run it

REM set line counter starts with 3
set c=3

REM a list of processes which can have very different names
set processes="processA.exe" "processB.exe" "processC.exe" "processD.exe"

REM checkpoint1 <--
echo on
for %%p in (%processes%) do (
  set ln%c%=taskkill /f /im %%p
  set /a c=%c%+1
  echo %c%
)
echo off

set lns=6
set cmd=start cmd.exe /c %ln1%
REM not sure why %%lns%% did not give the number 6
for /l %%i in (2,1,%%lns%%) do (
  REM i think i have another issue here below
  set cmd=!cmd! & !ln%%i!
)
echo %cmd%

At checkpoint1 inside the loop, the actual command lines in the console look like this:

set ln3=taskkill /f /im "processA.exe"
 set /a c=3+1
 echo 3
set ln3=taskkill /f /im "processB.exe"
 set /a c=3+1
 echo 3
set ln3=taskkill /f /im "processC.exe"
 set /a c=3+1
 echo 3
...

Which as you proberbly noticed, %c% did not increase. Even though I've got the delayedexpansion enabled.

Crericper
  • 1
  • 3

1 Answers1

0

Solution:

I just have figured out by replacing all %c% with !c! inside the loop... That is, according to another similar question answered by Magoo:

To access a variable in delayedexpansion mode, you need to use !var! in place of %var%.

Thanks.

Crericper
  • 1
  • 3