我知道如何創建一個批處理檔案來洗掉早于某個日期的檔案,但是有沒有辦法洗掉超過某個數量的最舊檔案?例如,如果一個目錄中有 3 個檔案,您可以洗掉最舊的檔案,只保留 2 個最新的檔案嗎?這將洗掉超過 3 天的檔案,但如何修改它,以便洗掉該目錄中超過 3 天的最舊檔案。
forfiles /p "D:\Daily Backups\myfiles" /s /d -3 /c "cmd /c del @file"
uj5u.com熱心網友回復:
獲取從新到舊排序的所有檔案的串列。然后遍歷這個串列,忽略前三個檔案并洗掉其他所有檔案。
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET /a counter=1
REM get an ordered list of all files from newest to oldest
REM you may want to edit the directory and filemask
FOR /f "delims=" %%a IN (
'dir /b /a-d /tw /o-d "backups\*.*"'
) DO (
REM only if the counter is greater than 3 call the deletefile subroutine
IF !counter! GTR 3 (
CALL :deletefile %%a
) ELSE (
ECHO KEEPING FILE: %%a
)
SET /a counter=!counter! 1
)
GOTO end
:deletefile
ECHO DELETING FILE: %1
REM DEL /F /Q %1 <-- enable this to really delete the file
GOTO :EOF
:end
SETLOCAL DISABLEDELAYEDEXPANSION
ECHO Script done!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/462616.html
標籤:批处理文件
