2

I am writing a batch script where I check the length of PDF file names in a dir. If the file name is greater than 3 characters long then I need to break out of the for loop. This should happen at the very first problem file. My issue is that I can't seem to find a way to break out of the loop.

This is the code that I have and the output I get. My problem is that the errorCnt variable that I am using to set between 0 and 1 never changes to 1 even though I am setting it

echo STARTING SCRIPT
setlocal

set errorCnt=0
for %%a in (test*.pdf) do (

    echo %%~a

    SET "fullname=%%a"
    SET "name=%%~na

    call :strlen result name

    call :finalresult

    echo Error count is %errorCnt%

    if %errorCnt%==1 (
        echo break
        goto :break
      )

)

:break

goto :EOF


:strlen <resultVar> <stringVar>
(   
    setlocal EnableDelayedExpansion
    set "s=!%~2!#"
    set "len=0"
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
        if "!s:~%%P,1!" NEQ "" ( 
            set /a "len+=%%P"
            set "s=!s:~%%P!"
        )
    )
)
( 
    endlocal
    set "%~1=%len%"
    exit /b
)

:finalresult
echo %name% - characters: %result%
if %result% GTR 3 GOTO error1

goto :EOF

:error1
echo ERROR: There are too many characters in this PDF filename.
set errorCnt=1

goto :EOF

OUTPUT:

STARTING SCRIPT
test1.pdf
test1 - characters: 5
ERROR: There are too many characters in this PDF filename.
Error count is 0
test2.pdf
test2 - characters: 5
ERROR: There are too many characters in this PDF filename.
Error count is 0
Sam B
  • 27,273
  • 15
  • 84
  • 121
  • The only place you set errorcnt to non-zero is just before the batch file exits, in the :error1 block. – Marc B Nov 13 '14 at 15:44
  • I set it there since I encountered the error. How should I handle the error check in for loop? – Sam B Nov 13 '14 at 16:00

1 Answers1

2

Ok I found my answer. The problem is that DOS / Batch treats for loop as one single command. What I mean is that if you set a variable before for loop is called then it remains the same no matter if you change it elsewhere in your code.

The work around is to use EnableDelayedExpansion.

Batch script for loop won't set variable

Once I change my code to this it works great.

echo STARTING SCRIPT

setlocal enabledelayedexpansion

...
rem notice the ! signs

if !errorCnt!==1 (
        echo break
        goto :break
      )

STARTING SCRIPT
test1.pdf
test1 - characters: 5
ERROR: There are too many characters in this PDF filename.
Error count is 1
break
Community
  • 1
  • 1
Sam B
  • 27,273
  • 15
  • 84
  • 121