batch script for loop and if statement not interacting properly

Solution 1:

I just added the ! to the variables within the FOR loop to ensure they are all expanded at execution time within the loop to ensure new set values are read accordingly to help get the final !maxfile! value as per each loop iteration.

Furthermore, I added the CD /D "%%~F0" to the line above the start of the FOR loop to ensure the directory is changed to the directory the script resides since you're not explicitly specifying the directory in your command example but I added an explicit example script below as well.

Batch Script (Implicit)

SETLOCAL ENABLEDELAYEDEXPANSION
SET "maxfile=1"
cd /d "%%~F0"
for /f %%i in ('dir /b note_*.txt') do (
    SET "archivename=%%~ni"
    SET "archivenumber=!archivename:~5!"
    if !archivenumber! GTR !maxfile! SET /a maxfile=!archivenumber!+1
)
echo !maxfile!
ENDLOCAL

Batch Script (Explicit)

SETLOCAL ENABLEDELAYEDEXPANSION
SET "maxfile=1"
SET "srcdir=C:\Folder\Path"
for /f %%i in ('dir /b "%srcdir%\note_*.txt"') do (
    SET "archivename=%%~ni"
    SET "archivenumber=!archivename:~5!"
    if !archivenumber! GTR !maxfile! SET /a maxfile=!archivenumber!+1
)
echo !maxfile!
ENDLOCAL

Further Resources

  • EnableDelayedExpansion

    Delayed Expansion will cause variables within a batch file to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL EnableDelayedExpansion command.


    When delayed expansion is in effect, variables can be immediately read using !variable_name! you can also still read and use %variable_name% that will show the initial value (expanded at the beginning of the line).

  • For

    Variable Substitutions (FOR /?)

    In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:

    %~I         - expands %I removing any surrounding quotes (")
    %~fI        - expands %I to a fully qualified path namey