Home > Software engineering >  Batch file FOR loop improvements
Batch file FOR loop improvements

Time:12-19

We've got code in productions, that checks file attributes (result of check.bat file1.bin returns 0 or 1) and restart user processes if necessary (if returned 1, then restart process). Code is working fine, but I just wanted to ask is there a way to improve it with FOR loop, since we really do the same thing every cycle, but with 1 to username, task name and filename

@echo off

:cycle1
FOR /F "tokens=* USEBACKQ" %%F IN (`check.bat file1.bin`) DO (SET var=%%F )
if %var% == 1 (taskkill /f /fi "USERNAME eq user1" & SCHTASKS /RUN /TN "task1")
goto cycle2

:cycle2
FOR /F "tokens=* USEBACKQ" %%F IN (`check.bat file2.bin`) DO (SET var=%%F )
if %var% == 1 (taskkill /f /fi "USERNAME eq user2" & SCHTASKS /RUN /TN "task2") 
goto cycle3

:cycle3
FOR /F "tokens=* USEBACKQ" %%F IN (`check.bat file3.bin`) DO (SET var=%%F )
if %var% == 1 (taskkill /f /fi "USERNAME eq user3" & SCHTASKS /RUN /TN "task3") 
goto eof

:eof
exit /b 0

CodePudding user response:

You can use a for /l loop to increment file numbers. I also made some other small changes to make the code simpler, no need for those code blocks:

@echo off
for /l %%a in (1,1,3) do for /F "delims=" %%F IN ('check.bat "file%%a.bin"') do (
    if %%F equ 1 taskkill /f /fi "USERNAME eq user%%a" & SCHTASKS /RUN /TN "task%%a"
)

However, I am sure your users and tasks are not called user1,2,3 and task,1,2,3 so you need to define your user and task variables and still use the number increments to select each use according to the bin file number:

@echo off & setlocal enabledelayedexpansion
set "u1=Steven"
set "u2=Maddy"
set "u3=Dan"
set "t1=taskname1"
set "t2=taskname2"
set "t3=taskname3"
for /l %%a in (1,1,3) do for /F "delims=" %%F IN ('check.bat "file%%a.bin"') do (
    if %%F equ 1 taskkill /f /fi "USERNAME eq !u%%a!" & SCHTASKS /RUN /TN "!t%%a!"
)
  • Related