Search code examples
batch-filefile-existsnot-exists

Batch - Ghost File Passing 'If Not Exist' Check


My Code

I have some straight forward code below that:

  1. Checks if a file exists in my directory
  2. Runs a for loop to get the first filename
  3. Does stuff based on filename
  4. Deletes the file
  5. Checks if any other files exist in directory (if yes, repeat, if not, move on)

    :MYLOOP
    IF NOT EXIST "%mypath%\*.*" GOTO nofile
    FOR %%F IN ("%mypath%\*.*") DO (
        set filenameWithExt=%%~nxF
        set filename=%%~nF
        set filepath=%%~pF
        )
    do other filename specific tasks
    
    del "%mypath%\%filenameWithExt%"
    
    IF NOT EXIST "%mypath%\*.*" GOTO nofile
    
    GOTO MYLOOP
    
    :nofile
    

My Issue

I've used this code repeatedly and its worked like a charm, but on my most recent use it looks like its finding a 'ghost' file. When there are no FILES (there is a single archive FOLDER) in the directory, the if not exist check from step 1 above somehow is still passing. As a result, the set code in the for loop results in:

The system cannot find the file specified.

And it then appears as though it tries to delete my directory, saying:

\\mypath*, Are you sure (Y/N)?

I then have to manually terminate an otherwise automated batch.

My Question

Why is it passing the if not exist check, rather than skipping to :nofile?

How can I account for this 'ghost' file (or if it is detecting the archive folder -- how else can I ignore it)?


Solution

  • The if exist test looks for anything in the directory.

    I'd restructure you code:

    :MYLOOP
    set "found1="
    FOR %%F IN ("%mypath%\*.*") DO (
        set filenameWithExt=%%~nxF
        set filename=%%~nF
        set filepath=%%~pF
        set "found1=Y"
        )
    if not defined found1 goto nofile
    
    do other filename specific tasks
    
    del "%mypath%\%filenameWithExt%"
    GOTO MYLOOP
    
    :nofile
    

    If the for finds no files, found1 will remain undefined so we go to the :nofile label, else we have a file to process. Having deleted the file, just go back to the beginning, clear the flag and repeat...