I'm trying to create batch file that will do the following:
- It will scan through all subfolders in specific directory for specific file.
- If it finds file within subfolder, all contents of this subfolder and subfolder itself will be deleted.
For example the file I'm looking for is "test.txt" and main folder is "C:\Test" with following structure:
\A
\B with test.txt
\C
\C\C0
\C\C1
\C\C2 with test.txt
\D
\D\D0
\D\D1 with test.txt
\D\D1\D10
\D\D1\D11
Each folder has some other random files in it.
In this example script should delete following folders and all their contents:
C:\Test\B
C:\Test\C\C2
C:\Test\D\D1
I tried several different scripts, but with no success. Batch file is placed directly in "C:\Test\"
First script I checked is:
for /R %%f in (test.txt) do @IF EXIST %%f @echo "%%f"
It properly listed only path to folders with text.txt inside. Because it worked, I tried following one to delete only files for test:
for /R %%f in (test.txt) do @IF EXIST %%f del /q /s /f "*.*"
It deleted all files in main folder and all subfolders where batch file is, along with batch file itself.
I tried to edit then several other scripts to match my conditions, but results were obvious. Last thing I was able to create is:
for /R %%p in (test.txt) do @IF EXIST %%p (rd "%%p" /s || del "*.*" /s/f)
I ommited here "/q" parameter to be able to see what it wants to delete. It finds properly first "text.txt" file. If "y" is chosen to delete this file, script returns error that this is not proper folder. Then it starts to delete files from main folder and all subfolders with batch file being first victim (it asks each time if I want to delete files in specific subfolder). Subfolders are not deleted, only their contents.
I'm out of ideas.