Page 1 of 1

Remove folder once it is empty!!!

Posted: 03 Apr 2010 06:34
by jamesfui
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:

Re: Remove folder once it is empty!!!

Posted: 05 Apr 2010 09:58
by avery_larry
Just try to remove the directory. If it's not empty, it will fail:


rd "c:\dir to be deleted"

Re: Remove folder once it is empty!!!

Posted: 11 Jul 2010 12:13
by dani8190
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

Re: Remove folder once it is empty!!!

Posted: 11 Jul 2010 15:14
by aGerman
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