What I need to do with a batch file is like this:
- Check how much video files are collected so far.
- Compare if the total size is bigger than the size I can afford.
- If it is under the space budget, then the batch finishes.
- If there are more than I can afford, I want to delete oldest files first.
- So I need to figure out what date/time is the oldest.
- I will delete files that are at the date/time.
- Go to the first step in order to see if I need to delete more.
This was little tricky without installing any external applications.
I had to make two separate batch files due to the syntax limitations on For loop.
One looks like this (c:\batch\delete_surveillance_find_oldest.bat):
@ECHO OFFIt takes a Date value as an input argument.
SET /a DATE_DIFF=%OLDEST_DATE% - %fdate%
IF NOT "x%DATE_DIFF:~0,1%" == "x-" SET OLDEST_DATE=%fdate%
It compares the date with an oldest date.
If it the date is older than the one that has been found, it updates it.
Another file is like this (c:\batch\delete_surveillance.bat):
IF NOT EXIST "%TargetDir%" GOTO :ERROR_ARG
IF NOT EXIST "%FIND_OLDEST%" GOTO :ERROR_ARG
REM SET DeleteCmd=ECHO
SET DeleteCmd=DEL /f
FOR /F "tokens=1,2,3" %%A IN (' dir /s "%TargetDir%" ^| FIND " File(s)" ') DO SET TotalSize=%%C
SET /a TotalSize=%TotalSize:,=%/1024/1024
ECHO Size limit: %MAX_SIZE_IN_MB%
ECHO Total size: %TotalSize% MB
SET /a SizeDiff=%MAX_SIZE_IN_MB% - %TotalSize%
IF NOT "x%SizeDiff:~0,1%" == "x-" GOTO :SPACE_ENOUGH
ECHO Space is not Enough...
ECHO Searching for the date of the oldest file...
SET /a OLDEST_DATE=99998877
FOR /F "tokens=1,2" %%A IN (' dir /s /a-d "%TargetDir%" ^| FIND "/" ' ) DO CALL "%FIND_OLDEST%" %%A
ECHO Oldest date found: %OLDEST_DATE:~0,4%/%OLDEST_DATE:~4,2%/%OLDEST_DATE:~6,2%
ECHO Deleting the oldest files...
FORFILES /p %TargetDir% /s /D -%OLDEST_DATE:~4,2%/%OLDEST_DATE:~6,2%/%OLDEST_DATE:~0,4% /c "cmd /c @FOR %%I IN (@path) DO @IF NOT EXIST %%~sI\NUL ( @ECHO @path & %DeleteCmd% /f @path )"
ECHO Let's see if we have enough space now.
ECHO There are enough space.
ECHO Input arguments or settings are incorrect.
ECHO TargetDir = %TargetDir%
ECHO FIND_OLDEST = %FIND_OLDEST%
This will follow the process I described above.