如何在批处理文件中运行脚本后的特定天数后永久删除特定文件

时间:2015-07-15 09:53:15

标签: windows date batch-file file-io cmd

我希望有一个小批处理文件脚本可以在 Windows XP,7,8 上运行,并在脚本执行一段时间后删除任何特定文件。

我尝试过类似的东西:

forfiles -p "C:\what\ever" -s -m *somefile.pdf* /D -<number of days> /C "cmd /c del @path"

但这不是我真正想要的,因为它正在删除超过特定时间的文件。有用的建议吗?

1 个答案:

答案 0 :(得分:0)

基本上有三种方法可以解决这个问题:

  • 保持批处理文件一直运行,在完成所需时间后删除文件并重新启动该过程。这是wOxxOm答案中使用的方法。

  • 使用Windows任务计划程序每N天执行一次“删除文件”命令。

  • 将批处理文件放在Startup文件夹中,以便每次用户登录时都会运行。批处理文件检查是否必须删除该文件才能执行此操作,计算下次的日期并将其存储在同伴中数据文件。这是下面批处理文件中使用的方法:

@echo off
setlocal EnableDelayedExpansion

rem Get today's date arranged as YYYYMMDD
rem (adjust lines below if MM/DD/YYYY is not the current locale date format)
for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
   set "MM=%%a" & set "DD=%%b" & set "YYYY=%%c"
)
set "today=%YYYY%%MM%%DD%"

rem Read next date from companion file
set /P nextDate=< NextDate.txt

if %today% lss %nextDate% goto :EOF

rem Delete the file, calculate next date and store it in companion file
del "C:\what\ever\somefile.pdf"

set days=5

set mon=0
for %%a in (31 28 31 30 31 30 31 31 30 31 30 31) do (
   set /A mon+=1
   set "daysPerMonth[!mon!]=%%a"
)
set /A Ymod4=YYYY %% 4, MM=1%MM% - 100, DD=1%DD% - 100 + days
if %Ymod4% equ 0 set "daysPerMonth[2]=29"
if %DD% gtr !daysPerMonth[%MM%]! set /A DD-=daysPerMonth[%MM%], MM+=1
if %MM% gtr 12 set /A MM=1, YYYY+=1
if %MM% lss 10 set "MM=0%MM%"
if %DD% lss 10 set "DD=0%DD%"

echo %YYYY%%MM%%DD%> NextDate.txt

请注意,您必须手动创建带有第一个日期的NextDate.txt文件,但可能会插入其他代码以管理此初始化步骤。