On a windows machine (win 7 or Win server 2008 R2) I have a batch script that copies some .config files to a backup folder.
I want to write another script that deletes the backup files created a week earlier.
There are plenty of suggestions on how to use FORFILES
(as example):
FORFILES /P "D:\Configs_Backup" /M *.config /D -7 /C "cmd /c del @file"
But this command uses the "modified" timestamp, while I need to use the creation date.
Without installing any third party program, is it possible via command console to achieve this?
try this, look at the output and remove the 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 works only for AM/PM
time format.
See if this helps - Keep the 5 *.config files (skip=5) with the most recent creation date
Test it on sample files.
@echo off
pushd "d:\folder"
del file2.tmp 2>nul
for /f "delims=" %%a in ('dir *.config /b /a-d ') 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"
I know this is an old post but I stumbled across it and it helped. I ended up going the route hinted at by @Gray as a comment and changed my .bat copy script to this so that it would update the modified date when copying rather than trying to solve it in the clean up script.
copy %1 %2 /y
copy /b %2+,, %2
https://superuser.com/questions/10426/windows-equivalent-of-the-linux-command-touch
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.