Alex McKenzie
Alex McKenzie

Reputation: 912

Calling different function on error. Windows Batch

I've got a little script that will check for new files in a folder, and it will print all of the PDF files. Whenever the print fails, the %errorlevel% variable will go up to 1. I'm trying to use an if statement with goto and labels to get it to work but I can't figure out what is going on.

The script is:

:printfile
echo printing %1
set fname=%1
set fullFname="print\STW_Print\STW_Printer_TEST\%fname:~1%
echo ERLVL: %errorlevel%
"C:\Program Files (x86)\SumatraPDF\SumatraPDF.exe" -silent -print-to "\\s8011\OPS_2055_IS" %
echo ERLVL: %errorlevel%
set logFilename=%DATE:~4,2%-%DATE:~7,2%-%DATE:~10,4%
if %errorlevel% neq 0 goto error
echo Moving %fname% to printed
move %fullFname% STW_printed
echo %time% %1 Printed on STWTEST and Moved>> Printlogs\TEST-%logFilename%-log.txt
goto eof
:error
echo Moving %fname% to failed
move %fullFname% STW_failed
echo %time% %1 Failed on STWTEST and Moved>> Printlogs\TEST-%logFilename%-log.txt
GOTO eof

:eof

The line that calls the script:

for /f "tokens=*" %%i in ('dir print\STW_Print\STW_Printer_TEST\*.pdf /b') do (call :printfile "%%i")

And my output:

printing "BADTEST (2) - Copy.pdf"
ERLVL: 0
ERLVL: 1
Moving "BADTEST (2) - Copy.pdf" to printed
    1 file(s) moved.
printing "BADTEST (2).pdf"
ERLVL: 0
ERLVL: 1
Moving "BADTEST (2).pdf" to printed
    1 file(s) moved.
printing "BADTEST (3) - Copy.pdf"
ERLVL: 0
ERLVL: 1
Moving "BADTEST (3) - Copy.pdf" to printed
    1 file(s) moved.

I can't figure out why it's not moving to failed. Any help would be greatly appreciated!

Upvotes: 0

Views: 78

Answers (1)

RGuggisberg
RGuggisberg

Reputation: 4750

It is because you check errorlevel after doing the SET command... which clears errorlevel. Move your 'set logfilename...' line farther up. Also, when using errolevel you can just do

if errorlevel 1 goto :error

Upvotes: 1

Related Questions