Search code examples
for-loopbatch-filewhile-loopgoto

Checking for File and not Running command till file doesn't exist in batch


I'm feeling a bit constrained by batch's limitations and unsure the best way to code some logic. I have a hybrid Batch/VBScript for printing and decided the best way to confirm the VBScript had finished was by utilizing an external file as a placeholder.

The logic is like this:

Batch Script --> Create tmpfile --> Run VBScript

VBScript --> Print Job --> Delete File

That part works, but in my "call script" I have an array of files that I use a FOR LOOP to iterate over and print, but I can't figure out how to code the logic WHILE FILE EXISTS DON'T RUN NEXT PRINT JOB. I have figured out how to "loop" until the file doesn't exist, but this uses GoTo statements and they don't work inside FOR LOOPS. I tried using "EXIT /B" which I thought just exits a function, but it just closed the main script all together.

Here is my "call script" which needs some help~

::This is a placeholder file to check if VBScript is running
SET File="%TEMP%\jobrunning.txt"
del /F /Q %File%

::Print Each File in Array
for /l %%n in (0,1,%arrsize%) do (
SET FILEPATH="FILEPATH=!file[%%n]!
GoTo file_exists
)

::Is Job Still Running?
:file_exists
   IF EXIST %File% (
       GoTo :file_exists
) ELSE (
ECHO %PFUNC% %FILEPATH%
%PFUNC% %FILEPATH%
EXIT /B
)

Solution

  • The issue was using GoTo w/ EXIT /B. GoTo just jumps to a LINELABEL, and EXIT /B exits PROCESS IE: The Script. CALL opens a SUBPROCESS and EXIT /B returns to the main PROCESS allow further code execution. (It's the same as calling an external script and closing it).

    This is what I ended up using to test and just deleted the file manually after each iteration of the array.

    @ECHO OFF
    setlocal enabledelayedexpansion
    
    
    
    ::This is a placeholder file to check if VBScript is running
    SET File="%TEMP%\jobrunning"
    del /F /Q %File%
    
    ::Set arrsize -1
    set  arrsize=4
    set  arrayline[0]=1A
    set  arrayline[1]=2A
    set  arrayline[2]=3A
    set  arrayline[3]=4A
    set  arrayline[4]=5A
    
    ::read it using a FOR /L statement
    for /l %%n in (0,1,%arrsize%) do (
    copy /y NUL %TEMP%\jobrunning.txt >NUL
    TIMEOUT 2
    CALL :file_exists
    echo !arrayline[%%n]!
    )
    PAUSE
    
    GoTo :EOF
    
    :Is Job Still Running?
    :file_exists
       IF EXIST %File% (
           GoTo :file_exists
    ) ELSE (
    EXIT /B
    )