File is older than 4 minutes in Batch file

As I commented above, pure batch is horrible at date math. Here’s a hybrid batch / JScript script that’ll compute the age of a file (edit: or directory) pretty easily. No need to worry about hour rollovers, day changes, daylight savings time, or any of that other garbage. It’s all easy peasy lemon squeeze-y based on milliseconds since midnight Jan 1, 1970.

@if (@CodeSection==@Batch) @then

:: age.bat filename.ext
:: get age of file in minutes

@echo off
setlocal

if "%~1"=="" echo Usage: age.bat filename.ext && goto :EOF
if not exist "%~1" echo %1 not found. && goto :EOF

for /f %%I in ('cscript /nologo /e:JScript "%~f0" "%~1"') do (
    echo %1 is %%I minutes old.

    rem :: Now use "if %%I gtr 4" here to take whatever actions you wish
    rem :: on files that are over 4 minutes old.

)

goto :EOF

:: end batch portion / begin JScript
@end

var fso = new ActiveXObject("scripting.filesystemobject"),
    arg = WSH.Arguments(0),
    file = fso.FileExists(arg) ? fso.GetFile(arg) : fso.GetFolder(arg);

// Use either DateCreated, DateLastAccessed, or DateLastModified.
// See http://msdn.microsoft.com/en-us/library/1ft05taf%28v=vs.84%29.aspx
// for more info.

var age = new Date() - file.DateLastModified;
WSH.Echo(Math.floor(age / 1000 / 60));

For more information on batch / JScript hybrid scripts, see this GitHub page. The style used above is similar to Hybrid.bat on that page.

Leave a Comment