Batch file to delete all folders in a directory except the newest folder

789 views Asked by At

I am trying to delete old backups in a specific folder after a new backup has been done. As i do not really have experience with DOS commands i mashed a couple of scripts i found on the internet into one:

::(C)2008 "BuckFix" www.winsupportforum.de
@echo off
setlocal

set workdir="M:\BACKUPS\CACHE_SSD\"
set folder=
:: get list of all folders, oldest first
dir %workdir% /AD /B /t:w /OD > %temp%folder.tmp
for /f "tokens=1* delims=" %%i in (%temp%folder.tmp) do set "folder=%%i"
del %temp%folder.tmp

::checking if its the right one...just for debugging
echo newest... %folder%

set filedir="M:\BACKUPS\CACHE_SSD\%folder%"

::delete all folders except %folder% ...but how?

pause

So picking the newest folder works fine but i don't know how to delete all folders except that one. I think it'll just be a simple for-loop but all my attempts failed so far. It has to be a safe method as it is a backup folder and i just want to keep the most recent backup. I had delete scripts that worked but when there was only one folder it deleted that one as well. And when the directory was empty it killed the whole directory.

1

There are 1 answers

6
npocmaka On BEST ANSWER
@echo off
setlocal

set "workdir=M:\BACKUPS\CACHE_SSD\"
set "folder="
for /f "tokens=* delims=" %%i in ('dir %workdir% /AD /B /TW /O-D') do (
    set "folder=%%~fi"
    goto :break
)
:break
echo newest... %folder%

for /f "skip=1 tokens=* delims=" %%i in ('dir %workdir% /AD /B /TW /O-D') do   (
    echo rd /s /q "%%~fi"
)

pause

Test this.Actual removing command is echoed .Delete echo in echo rd /s /q "%%~fi" if everything is ok.