批处理文件逻辑可根据文件名中的日期删除文件 [英] Batch file logic to delete files based on date in filename

查看:85
本文介绍了批处理文件逻辑可根据文件名中的日期删除文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在对.bat文件有一个看似无害的要求,我是第一次处理批处理代码...找到了一个页面

I now have a seemingly innocuous requirement to be put in a .bat file ,I am dealing with Batch code for the first time ...found a page here that deals with something similar but it takes the modified date as reference.

在特定的文件夹X中,通过解析文件名来删除所有早于N天的文件. 文件名格式为Name_YYYYMMDD.log

In a particular folder X , Delete all files older than N days by parsing through their file name. where file name format is Name_YYYYMMDD.log

但请注意: 1.不想将上次修改日期作为参考(其他程序/应用可能已访问/修改了日志) 2.没有安装其他实用程序的权限.

But note : 1. Do not want the last modified date as reference (log might have been accessed/modified by other programs/apps) 2.No permission to install other utilities.

  • FORFILES命令在此工作中效果很好(但唯一的缺点是它以修改日期"为参考)
  • 将Aacini的以下脚本调整为规范后,可以正常工作.
  • 由于其他条件使整个场景更加复杂,我们决定放弃批处理,而在Powershell或AutoIT中进行处理.

谢谢!.

推荐答案

下面的批处理文件将文件日期转换为朱利安天数,即连续的天数,并使用它来知道每个天数.参数中给出了删除文件的天数.

The Batch file below convert file date to Julian Day Number, that is a sequential number of days, and use it to know how many days old is each one. The number of days to delete files is given in the parameter.

@echo off
setlocal EnableDelayedExpansion

rem Get Julian Day Number of today's date
rem The assumed format is MM/DD/YYYY, change C-A-B order in accordance with your locale
for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
   set todayDate=%%c%%a%%b
)
call :DateToJDN %todayDate% todayJDN=

for /F "tokens=1-3 delims=_." %%a in ('dir /B /A-D *.*') do (
   call :DateToJDN %%b fileJDN=
   set /A daysOld=todayJDN - fileJDN
   if !daysOld! gtr %1 (
      echo File "%%a_%%b.%%c" is !daysOld! days old
   )
)
goto :EOF

:DateToJDN yyyymmdd jdn=
set yyyymmdd=%1
set /A yyyy=%yyyymmdd:~0,4%, mm=1%yyyymmdd:~4,2% %% 100, dd=1%yyyymmdd:~6% %% 100
set /A a=(mm-14)/12, %2=(1461*(yyyy+4800+a))/4+(367*(mm-2-12*a))/12-(3*((yyyy+4900+a)/100))/4+dd-32075
exit /B

测试此程序,并将echo File "%%a_%%b.%%c" ...命令更改为所需的del "%%a_%%b.%%c".

Test this program and change the echo File "%%a_%%b.%%c" ... command by the desired del "%%a_%%b.%%c" one.

参考: http://www.hermetic.ch/cal_stud/jdn.htm#补偿

这篇关于批处理文件逻辑可根据文件名中的日期删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆