如果文件命名以,如下命名規則命名
文件名稱爲:20190101xxxxx.xxxxx
xxxxx代表爲任意字符
腳本內容爲:
@echo off
rem 使用相對路徑
rem set SrcDir="%cd%\dict"
rem echo %prog_path%
rem 使用絕對路徑
set SrcDir=D:\vpt\Snapshot
rem 指定天數
set DaysAgo=1
:start
>"%temp%/DstDate.vbs" echo LastDate=date()-%DaysAgo%
>>"%temp%/DstDate.vbs" echo FmtDate=right(year(LastDate),4) ^& right("0" ^& month(LastDate),2) ^& right("0" ^& day(LastDate),2)
>>"%temp%/DstDate.vbs" echo wscript.echo FmtDate
for /f %%a in ('cscript /nologo "%temp%/DstDate.vbs"') do (
set "DstDate=%%a"
)
set DstDate=%DstDate:~0,4%%DstDate:~4,2%%DstDate:~6,2%
echo "%DstDate%"
setlocal enabledelayedexpansion
for /r "%SrcDir%" %%a in (*.*) do (
set "FileDate=%%~na"
set "FileDate=!FileDate:~0,8!"
if "!FileDate!" leq "%DstDate%" (
if exist "%%a" (
echo del /f /q "%%a"
del /f /q "%%a"
)
)
)
endlocal
:: pause
choice /t 5 /d y /n >nul
goto start
上述代碼中:
SrcDir爲要刪除的目錄
DaysAgo爲刪除多少天以前的內容
這句話要按需修改:set DstDate=%DstDate:~0,4%%DstDate:~4,2%%DstDate:~6,2%
例如:文件名內容包含有20190101,則上述set DstDate=%DstDate:~0,4%%DstDate:~4,2%%DstDate:~6,2%
文件名內容包含有2019-01-01,則上述set DstDate=%DstDate:~0,4%-%DstDate:~4,2%-%DstDate:~6,2%
這段代碼的作用是將當前系統的日期減去DaysAgo後進行拆裝組合。
2019-02-14減去30=2019-01-15,拆裝後爲20190115
接下來修改下面的話,這句話意思是截取文件名中的日期,我這裏的日期是從第七位開始的,截取了8位。
set "FileDate=!FileDate:~7,8!"
截取的日期會和上面的日期進行對比,滿足條件則刪除。
再加一個go語言寫的循環就能循環執行了
:start
rem 要執行的腳本代碼
choice /t 5 /d y /n >nul
goto start
代碼 choice /t 5 /d y /n >nul 中的 5表示隔5秒鐘執行一次