关于bat:批处理脚本实现文件自动清理

11次阅读

共计 1784 个字符,预计需要花费 5 分钟才能阅读完成。

依照文件的最新批改日期工夫进行删除

@REM @Author: chasi
@REM @Date:   2020-11-09 14:49:16
@REM @Last Modified by:   chasi
@REM Modified time: 2020-11-10 09:14:16

@echo off

title 清理 Tomcat 日志文件

set log_dir="D:\apache-tomcat-8.5.27\logs"

set bak_dat=10

forfiles /p %log_dir% /S /M *.log /D -%bak_dat% /C "cmd /c echo 正在删除 @relpath 文件… & echo. & del @file"

forfiles /p %log_dir% /S /M *.txt /D -%bak_dat% /C "cmd /c echo 正在删除 @relpath 文件… & echo. & del @file"

依照文件中蕴含的日期格局间隔以后工夫的距离天数进行删除

@REM @Author: chasi
@REM @Date:   2020-11-09 15:39:53
@REM @Last Modified by:   chasi
@REM Modified time: 2020-11-25 16:56:35
@echo off

rem 应用绝对路径,Tomcat 目录下寄存日志的具体门路(以理论装置门路为准)set SrcDir="D:\apache-tomcat-8.5.27\logs"

rem 指定日志保留天数
set DaysAgo=10

:: 计算距离天数
>"%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%

:: 开启变量提早
setlocal enabledelayedexpansion
set indexofstr=0

:: 查找含有指定日期格局字符串的文件
for /r "%SrcDir%" %%a in (*.*) do (
    set "FileDate=%%~na"
    ::echo indexofstr:!indexofstr!
    call:IndexOfStrFunc "%%~na",indexofstr
    ::echo indexofstr:!indexofstr!
    set  indexofstr=!indexofstr!
    ::echo %indexofstr%
    call set FileDate=%%FileDate:~!indexofstr!,10%%
    if "!FileDate!" leq "%DstDate%" (
        if exist "%%a" (
            ::echo del /f /q "%%a"
            del /f /q "%%a"
        )
    )

)
:: 敞开变量提早
endlocal

::echo 输入结束,按任意键退出 &&pause>nul&&exit

:IndexOfStrFunc
::IndexOfStrFunc 函数:查找字符串内第一个字符为 2 - 3 的索引地位

set str1=%~1
set str=%str1%
set num=0

:next
set ch1=2
if not "%str%"=="" (
set /a num+=1

:: 循环局部
:loop
if not "%ch1%" == "3" (
    if "!str:~0,1!"=="%ch1%" goto last
    set /a ch1=ch1+1
    goto loop
)
set "str=%str:~1%"
goto next
)
set /a num=0

:last
::echo 字符 '%ch1%' 在字符串 "%str1%" 中的首次呈现地位为 %num%
set next=1
set /a indexofstr=%num%-%next%

goto:eof

PS:windows 端增加定时工作脚本,运行 cmd,输出 compmgmt.msc 后依照定时工作的增加步骤要求进行填写。

正文完
 0