以下是一个解除占用并删除目录下创建时间在三天及以前的文件的bat脚本:

@echo off
setlocal

set 'target_directory=C:\目标目录'  // 将'目标目录'替换为你要操作的目录路径
set 'days_to_keep=3'

forfiles /p "%target_directory%" /s /m * /c "cmd /c if @isdir==FALSE echo @path @fdate @ftime" > temp.txt

for /f "tokens=1,2,3,*" %%A in (temp.txt) do (
    set 'file_date=%%B'
    set 'file_time=%%C'
    set 'file_path=%%D'
    call :process_file
)

del temp.txt
exit /b

:process_file
rem 获取当前日期和时间
for /f "tokens=2 delims==" %%x in ('wmic OS Get localdatetime /value') do set 'current_datetime=%%x'

rem 提取当前日期和时间中的年、月和日
set 'current_year=%current_datetime:~0,4%'
set 'current_month=%current_datetime:~4,2%'
set 'current_day=%current_datetime:~6,2%'

rem 提取文件日期中的年、月和日
set 'file_year=%file_date:~0,4%'
set 'file_month=%file_date:~4,2%'
set 'file_day=%file_date:~6,2%'

rem 计算文件的创建日期与当前日期之间的天数差
set /a 'date_diff=(%current_year% - %file_year%) * 365 + (%current_month% - %file_month%) * 30 + (%current_day% - %file_day%)'

if %date_diff% gtr %days_to_keep% (
    rem 解除占用文件
    attrib -r "%file_path%"
    
    rem 删除文件
    del "%file_path%"
    echo Deleted: %file_path%
)

exit /b

请将脚本中的C:\目标目录替换为你要操作的目录路径,并根据需要将days_to_keep变量设置为你想要保留的天数。运行脚本后,它将解除占用并删除目录下创建时间在三天及以前的文件。

自动删除目录下三天前的文件并解除占用 - BAT脚本

原文地址: https://www.cveoy.top/t/topic/o9dy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录