简体   繁体   中英

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

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.

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM