_
_
_umr2016-09-21 19:15:55
cmd/bat
_umr, 2016-09-21 19:15:55

How to delete old folders using a batch file?

I have a script that creates a backup folder and the name of the folder is a number. How to delete the old (yesterday's) folder?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
res2001, 2016-09-21
@Umr001

The
dir /a:d /o:-d /t:w /b %DIRNAME% command
will return a list of subdirectories in the given directory, sorted in descending order by modification date, skip the first N entries from this list (N is the number of days for which you want to backup) , delete the rest.
Schematically, the code will look like this:

set "DIRNAME=c:\TEMP"
set "N=10"
for /f "usebackq skipto=%N% tokens=* delims=" %%a in ('dir /a:d /o:-d /t:w /b %DIRNAME%') do (
 echo.RD /S /Q "%DIRNAME%\%%~a"
)

I did not check the code for performance, but I think the idea should be clear.
Help:
dir /?
for /?
rd/?

E
Ethril, 2016-09-21
@Ethril

Well, the collective farm .... forfiles /?

_
_umr, 2016-09-21
@Umr001

Might be useful to someone:

set dt=%Date%  
set /a dtDay=%dt:~0,2%
set dtMonth=%dt:~3,2%
set /a dtYear=%dt:~-4%
set /a dtDay=%dtDay%-1
RD /S /Q "F:\path_to_folder\%dtDay%.%dtMonth%.20%dtYear%"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question