I have files in a folder 'FILEPATH', each file has different created date and modified date(modified date is less than created date). I want to delete the files with created date greater than 10days. I used below command but it works on modified date.
ROBOCOPY %FILEPATH% %DUMPFOLDER% /move /minage:10
del %DUMPFOLDER% /q
On some forums its written that minage refers to created date but it's referring to modified date while executing. Am I doing something wrong here? Or is there any other alternate.
Unfortunately, there's no easy way to do this. The only commands of which I'm aware that can deal with file creation dates are dir /t:c
and wmic datafile
. There could be others, but there are none that simplify performing date math as forfiles
or robocopy
do.
Since date math in batch is cumbersome anyway, in this situation it makes sense to borrow from another runtime environment -- PowerShell, for example, or VBScript or JScript. The Windows Scripting Host FileSystemObject
's File
Object has properties for DateCreated
, DateLastAccessed
, and DateModified
. With JScript, getting a file's age based on its DateCreated
property is simply a matter of JavaScript Date()
arithmetic.
Here, salt this .bat
script to taste:
@if (@CodeSection == @Batch) @then
@echo off
setlocal
set "FILEPATH=c:\path\to\whatever"
set "age=10"
for %%I in ("%FILEPATH%\*") do (
call :getAge result "%%~fI"
setlocal enabledelayedexpansion
if !result! gtr %age% (
echo %%~nxI created !result! days ago and should be deleted
rem del "%%~fI"
) else (
echo %%~nxI is new ^(created !result! days ago^)
)
endlocal
)
goto :EOF
:getAge <return_var> <filename>
for /f "delims=" %%I in ('cscript /nologo /e:Jscript "%~f0" "%~2"') do set "%~1=%%I"
goto :EOF
@end
// JScript portion
var fso = WSH.CreateObject('scripting.filesystemobject'),
created = fso.GetFile(WSH.Arguments(0)).DateCreated,
age = new Date() - created;
WSH.Echo(Math.floor(age / 1000 / 60 / 60 / 24));
If you want something simpler, you could employ wmic datafile
and get the first 8 digits of get creationdate
like this cat does , but his solution doesn't take into account time of day. Such a method might inappropriately delete files that are 9 days, 23 hours old. Then there's also the problem of calculating days across new months. The JScript method above tests file age based on the current moment, rather than based on midnight; and will handle spanning months, years, and leap years with no conscious effort.
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.