Question

I need to delete all folders and subfolders where a specified file does NOT exist in the root but leave all files and folders if the specified file is found. The file will be in the root. i.e. c:\list\12345\1\1 12345 contains the txt file "complete", so leave this folder and file structure alone. i.e. c:\list\67891\1\1 67891 does NOT contain txt file "complete", so delete 67891 and all its subfolders and files.

I've tried nothing. I am completely new to cmd shell. Or maybe theres a util that will do this.

Was it helpful?

Solution

EDITED This is untested. It creates file.bat.txt for you to check and then you can run it if it has the right folders in it. After you check file.bat.txt and are happy with it then you can rename it to file.bat and run it to remove the folders.

What the code below does is: create a list of all paths to any file named complete.txt under c:\list and then compares only the root folder of every folder in the main folder. If the root folder is not found in the list then it echoes the RD command to remove it into file.bat.txt

@echo off
set "folder=c:\list"
if not defined folder goto :EOF
dir "%folder%\complete.txt" /b /s /a-d >temp.tmp
del file.bat.txt 2>nul
for /f "delims=" %%a in ('dir "%folder%" /b /ad ') do (
find /i "%folder%\%%a" <"temp.tmp" >nul || >>file.bat.txt echo rd /s /q "%folder%\%%a"
)
:del temp.tmp

OTHER TIPS

@echo off
    setlocal enableextensions disabledelayedexpansion
    for /r "c:\list" %%f in (.) do ( 
        dir /s /b "%%~ff\complete.txt" >nul 2>&1 || echo rd /s /q "%%~ff" 
    )
    endlocal

Adapt as needed. When output to console is correct, remove the echo command before rd to remove the directories.

While echo command is present, the list of directories to delete will include complete branches, but when echo is removed, and rd is working, since the first parent in a disposable branch is removed, all his descendants are deleted in the same operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top