How do you create a batch script that will delete the oldest files when a folder size limit is reached
I have found plenty of solutions to similar problems, but I wonder is it possible to create a script that deletes the oldest files once a preset folder size 开发者_StackOverflow中文版limit is reached?
You need to solve two problems.
First, you need to calculate the folder size. Use a code similar to this
:foldersize
set sz=0
for %%F in (%1\*.*) do (
set /a kb = %%~zF / 1024
set /a sz = !sz! + !kb!
echo %%F %%~zF !kb! !sz!
)
goto :eof
Second, you need to recognize older files and delete them until a size is reached
for /F "tokens=*" %%F in ('dir /A-D /OD /B %1\*.*') do (
if !sz! geq !targetsize! (
call :filesize %1\%%F
del %1\%%F
set /a sz = !sz! - !kb!
) else (
goto :eof
)
)
goto :eof
:filesize
set /a kb = %~z1 / 1024
goto :eof
Putting all pieces together...
@echo off
setlocal enabledelayedexpansion
set /a targetsize=%2
call :foldersize %1
for /F "tokens=*" %%F in ('dir /A-D /OD /B %1\*.*') do (
if !sz! geq !targetsize! (
call :filesize %1\%%F
del %1\%%F
set /a sz = !sz! - !kb!
) else (
echo Done... %1 size is now !sz! KB
goto :eof
)
)
echo Not completely done... %1 size is still !sz! KB
goto :eof
:filesize
set /a kb = %~z1 / 1024
goto :eof
:foldersize
set sz=0
for %%F in (%1\*.*) do (
set /a kb = %%~zF / 1024
set /a sz = !sz! + !kb!
)
goto :eof
Test and test and test, as it does not move the files to the trash but it deletes the files permanently.
Also, you may want to specify /F
option in case you have read-only files you want to delete.
In the case you have subfolders in the folder and you want to take those into the account of folder size and you want to delete the older files, things may get more complicated.
The calculation of the size is this
:foldersizerecurse
set sz=0
for /F %%F in ('dir /OD /B *.*') do (
set /a kb = %%~zF / 1024
set /a sz = !sz! + !kb!
echo %%F %%~zF !kb! !sz!
)
goto :eof
And deleting the older files.. you need to pipe the 'dir /S' command output to sort and sort by date. I feel tired to do it.
精彩评论