Dos - Loops

By xngo on November 26, 2019

Goto: Loop until condition met

Use goto to loop until the service status is STOPPED.

REM -- Change SERVICE NAME and COMPUTER NAME to your situation.
set service_name="SERVICE NAME"
set computer_name="COMPUTER NAME"

REM -- Stop service and wait until status is STOPPED.
sc \\%computer_name% stop %service_name%
:loop
sc \\%computer_name% query %service_name% | find "STOPPED"
if errorlevel 1 (
    timeout 1 /nobreak
    goto loop
)

Goto: Loop with increment

Using goto to loop until %i% is greater than %Max%.

@echo off
 
set max=10
set i=0
 
:loop
if %i% gtr %Max% goto GetOut
    echo %i%
 
    set /A i=i+1
goto loop
 
:GetOut

FOR loop in a set

REM Loop through a defined set.
@ECHO OFF
FOR %%W IN (a B C d E whatever) DO (
ECHO %%W
)

REM ========================= OR =========================

REM Loop through each line returned by DIR command.
REM By default, the delimiter is a space. Therefore, it will not properly handle filenames with spaces.
REM To avoid this issue, use "delims=" to set the delimiter to nothing. Afterward, it will take the complete line.
FOR /F "delims=" %%W IN ('dir /s/b *.*') DO (
ECHO %%W
)

REM ========================= OR =========================

REM Use FOR loop to loop X times.
REM Syntax: FOR /L %variable IN (start,step,end) DO
FOR /L %%V IN (1,1,20) DO (
ECHO %%V
)

REM ========================= OR =========================
REM Example using token and delimiter
REM time command will output "The current time is: HH:MM:SS.mm".
REM "HH:MM:SS.mm" is the 5th token in the time command.
FOR /F "tokens=5 delims= " %%i IN ('echo ^| time ^| find "current" ') DO (
ECHO %%i
)

Can't increment environment variables within the FOR loop DOS doesn't increment environment variables within the FOR loop. However, you can call a subroutine outside of the FOR loop and do your increment there, like this:

@ECHO OFF
 
set i=1
FOR /L %%V IN (1,1,3) DO (
REM Will always be 1.
ECHO In Loop: %i%

REM Call Increment subroutine outside of the FOR loop.
CALL :Increment
)
 
ECHO "Other commands here after the loop."
 
goto :EOF
 
:Increment
  ECHO ___________Out of Loop: %i%
  set /a i+=1
  goto :EOF

Note: set /A does integer arithmetic only.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.