Need a way to delete a folder (rd/rmdir) if it contains only one specific file within. If there are any other files or subfolders, ignore it. Trying to do so with as little code as possible. Currently, I'm doing this...
If Exist "C:\Folder\SubFolder\filename.txt" Move /Y "C:\Folder\SubFolder\filename.txt" "%TEMP%"
If Not Exist "C:\Folder\SubFolder\*" RD "C:\Folder\SubFolder" /Q /S
However, even though the folder contains no files, the folder is never deleted.
Is this possible within a batch file? Thanx in advance.
you can use
findto count the number of files in the directory and thenfindstrto determine the errorlevel and simply use conditional operator&&No need to check if the file exists either, you can redirect stderr to
nulwhen the file is not found.Edit
As you mentioned that you now only want to move the file if it is the only file in the directory, a few amendments in the current code sorts that out:
This time, we check to see if there is only 1 item (file or dir) in the folder, if it is, we test to see if it is
filename.txtif not, then we will skip the code block, if it is, move the file and remove the directory.I created variables for you as
_dirandfnamethat way you only update those two fields instead of all over the code.