Batch delete files older than a specific time

Batch delete files before a specific time.
Use the for command to read the result of dir /tc /od /a, which can be divided into 4 segments. The first two segments are the date and time, the third segment is the directory or file size, and the fourth segment is the file. Name or directory name. Then compare the first and second paragraphs with the required time to decide whether to delete the file

@echo off
rem cd /d f:/temp
rem mDateTime格式: yyymmddHHmm
set mDateTime=200608161907
for /f "skip=4 tokens=1,2,3,4* delims=<>" %%i in ('dir /a /-c /tc /o-d') do call :proc %%i %%j %%k %%l
goto end

:proc
set aDate=%1
set aTime=%2
set aType=%3
set aFile=%4
set aDatetime=%aDate:~0,4%%aDate:~5,2%%aDate:~8,2%%aTime:~0,2%%aTime:~3,2%
if /i "%aDateTime%" lss "%mDateTime%" (if NOT "%aType%"=="DIR" attrib "%aFile%" -r -h -s && del "%aFile%")

:end
 

But there will be some problems with the above, mainly because if can't compare large numbers, 200608161907 is too big for if. We can compare the date first, and then compare the time, but there are more if statements, or a compromise, using two years:

rem mDateTime 格式: ymmddHHmm
set mDateTime = 0608161907
……
set aDatetime =% aDate: ~ 2.2 %% aDate: ~ 5,2 %% aDate: ~ 8,2 %% aTime: ~ 0.2 %% aTime: ~ 3.2%

 

-------------------------------------------------- ------------------------------
Supplement:


# Xiaozhang published on 2006-09-19 09:03:00 

Windows 2003 has a command Forfiles, such as:
Forfiles /D -30 /C "cmd /c echo @fname" is 30 days ago. You can copy the 2003 Forfiles.exe file under 2000.
forfiles /D -4 /C "cmd /c del @file" Delete files 4 days ago. Hu Xiaoming's note


In addition, if you keep the last n files, it is easier. For example, keep the last 30 bak files:
for /f "skip=30" %i in ('dir *.bak /tc /od /b') do del% i 


This article is from the CSDN blog, please indicate the source for reprinting: http://blog.csdn.net/scz123/archive/2006/09/12/1213907.aspx

Guess you like

Origin blog.csdn.net/boy_hxm/article/details/5701584