• cmd UNC forfiles ::BATCH FILE FOR DELETE OLD FILES BY LAST ACCESS DATE
    ::AUTHOR "Nicolas Brousse"
    @ECHO OFF

    :: FIRST ARGS MUST BE THE PATH TO THE DIRECTORY TO PURGE
    :: SECOND ARGS MUST BE A NUMBER OF DAYS
    IF [%1] == [] ( GOTO :MISSING ) ELSE ( SET PURGE_DIR=%1 )
    IF [%2] == [] ( GOTO :MISSING ) ELSE ( SET DAY_LIMIT=%2 )

    :: WE GET THE PC LOCAL DATE DELIMITER (contrib from Mike Bikoulis)
    FOR /F "skip=4 tokens=3" %%y IN ('REG QUERY "HKCU\Control Panel\International" /v sDate') DO (
    SET DATE_DELIM=%%y
    )

    :: WE CHECK THE PC LOCAL SHORT DATE FORMAT
    FOR /F "skip=4 tokens=2* delims= " %%y IN ('REG QUERY "HKCU\Control Panel\International" /v sShortDate') DO (
    IF NOT "%%z" == "dd%DATE_DELIM%MM%DATE_DELIM%yyyy" GOTO :DATEFORMAT
    )

    :: SET CURRENT DATE MINUS DAYS ARGUMENT
    SET YEAR=%DATE:~6,4%
    SET MONTH=%DATE:~3,2%
    SET DAY=%DATE:~0,2%

    IF %MONTH:~0,1% EQU 0 ( SET MONTH=%MONTH:~1,1% )
    IF %DAY:~0,1% EQU 0 ( SET DAY=%DAY:~1,1% )

    SET /A LIMIT_UNIX_TIMESTAMP = (((%YEAR% 365) + (%MONTH% 31) + %DAY%) 24 60 ) — ( %DAY_LIMIT% 24 60 )

    :: PARSE THE DIRECTORY TO PURGE THEN CHECK FILES ON THEIR LAST ACCESS DATE
    FOR /F "usebackq delims=" %%a IN (`DIR /A:-D /B /S %PURGE_DIR%`) DO (
    SET CURRENT_FILE=%%a
    IF EXIST "%%a" (

    ECHO ---------------------------------------------------------
    ECHO TEST "%%a"

    FOR /F "usebackq skip=5 tokens=1" %%b IN (`DIR /T "%%a"`) DO (
    CALL :TESTSTRING %%b
    )
    )
    )

    GOTO :END

    :: GET FILE LAST ACCESS DATE
    :TESTSTRING
    FOR /F "tokens=1-3 delims=%DATE_DELIM%" %%c IN ("%1") DO (
    IF NOT [%%e] == [] (
    CALL :TESTDATE %%e %%d %%c
    )
    )
    GOTO :END

    :: TEST DATE WITH LIMIT_UNIX_TIMESTAMP
    :: DELETE TOO OLD FILES, WE COULD DO AN ERASE BUT IT'S LESS SECURE
    :TESTDATE

    SET YEAR=%1
    SET MONTH=%2
    SET DAY=%3

    IF %MONTH:~0,1% EQU 0 ( SET MONTH=%MONTH:~1,1% )
    IF %DAY:~0,1% EQU 0 ( SET DAY=%DAY:~1,1% )

    SET /A FILE_UNIX_TIMESTAMP = ((%YEAR% 365) + (%MONTH% 31) + (%DAY% 1 )) 24 * 60

    ECHO FILE_UNIX_TIMESTAMP = %FILE_UNIX_TIMESTAMP%
    ECHO LIMIT_UNIX_TIMESTAMP = %LIMIT_UNIX_TIMESTAMP%

    IF %FILE_UNIX_TIMESTAMP% LSS %LIMIT_UNIX_TIMESTAMP% (
    IF EXIST "%CURRENT_FILE%" (
    ECHO DELETE "%CURRENT_FILE%"
    DEL /Q /F "%CURRENT_FILE%"
    )
    )

    GOTO :END

    :MISSING
    ECHO USE : %0 [PATH] [DAYS]
    GOTO :END

    :DATEFORMAT
    ECHO THIS PC HAS MUST HAVE A SHORT DATE FORMAT LIKE dd%DATE_DELIM%MM%DATE_DELIM%yyyy
    GOTO :END

    :END

Replies (0)