Remove folder once it is empty!!!

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
jamesfui
Posts: 50
Joined: 27 Mar 2010 23:00

Remove folder once it is empty!!!

#1 Post by jamesfui » 03 Apr 2010 06:34

hi everyone..
i need to remove certain folders once it is checked empty!!
what is the script to do that?

for example,
c:\reports\2008\*.doc

once all the files are moved to,
c:\reports\2010\*.doc

the bat will check whether the folder '2008' is empty or not,
if empty, delete the folder but if still got files even hidden one,
that folder will retain & display a msg showing that folder still got file exist in it!!

thanks!! :wink:

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

Re: Remove folder once it is empty!!!

#2 Post by avery_larry » 05 Apr 2010 09:58

Just try to remove the directory. If it's not empty, it will fail:


rd "c:\dir to be deleted"

dani8190
Posts: 7
Joined: 17 Mar 2010 03:15

Re: Remove folder once it is empty!!!

#3 Post by dani8190 » 11 Jul 2010 12:13

hmmm how about this?

cd\
cd c:\reports\2008
if not exist *.doc goto delete


:delete
cd\
cd reports
rd /S /Q 2008
exit

hope it helps

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Remove folder once it is empty!!!

#4 Post by aGerman » 11 Jul 2010 15:14

dani8190 wrote:cd\
cd c:\reports\2008
if not exist *.doc goto delete


:delete
cd\
cd reports
rd /S /Q 2008
exit


No. If you found no *.doc files you jump to :delete. This is OK, but what happens if *.doc files are found?! The CMD will interprete the next line (it's :delete too). Think about it and correct your code (it's easy).

BTW avery_larry is right. But it also wouldn't remove the folder if there are (empty) subfolders inside.
Another possibility:

Code: Select all

@echo off &setlocal
dir /a-d /b /s "c:\reports\2008" 2>nul | findstr . >nul &&(
  echo folder and/or subfolders contain files
)||(
  echo folder and/or subfolders are empty
  rd /s /q "c:\reports\2008"
)
pause


Regards
aGerman

Post Reply