Script package to delete files older than X days (based on creation date, not modified date)

On a Windows machine (win 7 or Win server 2008 R2), I have a script package that copies some .config files to the backup folder.
I want to write another script that deletes backup files created a week before.

There are many suggestions on how to use FORFILES (as an example):

 FORFILES /P "D:\Configs_Backup" /M *.config /D -7 /C "cmd /c del @file" 

But this command uses a β€œmodified” timestamp, while I need to use the creation date.

Without installing a third-party program, is this possible using the command console?

+4
source share
2 answers

try this, look at the output and delete echo if it looks good:

 @ECHO OFF &SETLOCAL ENABLEDELAYEDEXPANSION SET /a XDay=7 CALL :DateToJDN "%DATE%" JDNToday FOR /r "D:\Configs_Backup" %%a IN (*.config) DO ( FOR /f "tokens=1,4*" %%b IN ('dir /tc "%%~a"^|findstr "^[0-9]"') DO ( CALL :DateToJDN "%%b" filedate SET /a diffdays=JDNToday-filedate IF !diffdays! gtr %XDay% ECHO DEL /F /Q "%%~a" ) ) GOTO :eof :DateToJDN "DD mm/dd/yyyy" jdn= setlocal set date=%~1 set /A yy=%date:~-4%, mm=1%date:~-10,2% %% 100, dd=1%date:~-7,2% %% 100 set /A a=mm-14, jdn=(1461*(yy+4800+a/12))/4+(367*(mm-2-12*(a/12)))/12-(3*((yy+4900+a/12)/100))/4+dd-32075 endlocal & set %2=%jdn% exit /B 

Note: this only works for AM/PM time format.

+5
source

See if this helps: save 5 * .config files (skip = 5) with the most recent creation date
Check it out on samples.

 @echo off pushd "d:\folder" del file2.tmp 2>nul for /f "delims=" %%a in ('dir *.config /b /ad ') do call :getcreationdate "%%~fa" sort /r <file2.tmp >file.tmp for /f "skip=5 tokens=1,*" %%a in (file.tmp) do del "%%~b" del file.tmp file2.tmp popd pause goto :EOF :getcreationdate set "file=%~1" set "file=%file:\=\\%" WMIC DATAFILE WHERE name="%file%" get creationdate | find "." >file.tmp for /f %%b in (file.tmp) do set dt=%%b set dt=%dt:~0,8%_%dt:~8,6% del file.tmp >>file2.tmp echo %dt% "%~1" 
+1
source

Source: https://habr.com/ru/post/1492677/


All Articles