Batch File to Delete a folder if it doesnt contain a specific file

I have a folder with loads of subfolders. I need a batch file that looks down the list of subfolders and checks if a specified file exists. If the file does not exist then the sub folder can be deleted.

This needs to run on Windows 7 workstations.

I am getting my syntax mixed up in my for /f and if exist commands:

for /f /f%% in ('dir /b c:\test') do if exist "test.txt" rename c:\test\%% tobedeleted

I think I am either trying to do to much in one argument or am missing something vital.


Solution 1:

If the file does not exist then the sub folder can be deleted.

You need something like the following:

echo off
setlocal enableDelayedExpansion
for /f %%i in ('dir /a:d /b /s c:\test') do (
  set _dir=%%i
  if exist !_dir!\test.txt (
    rem do nothing
    ) else (
    echo rd !_dir!
    )
  )
endlocal

Notes:

  • Remove the echo before rd when you are sure the correct directories will be deleted.
  • Add /s to rd if the directory contains subdirectories.
  • Add /q to rd to remove Y/N confirmation.

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • dir - Display a list of files and subfolders.
  • if - Conditionally perform a command.
  • enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
  • rd - Delete folder(s).
  • for /f - Loop command against the results of another command.