Batch Scripting, For using the results of a dir
-
19-09-2019 - |
Question
I'm trying to write a small batch script that will delete files old files from a directory. The first parameter is the directory for the script to look into, and the second is the number of files to preserve.
rem @ECHO OFF
rem %1 is the path in which to look for the files
rem %2 is the number of recent files to preserve
if [%1] EQU [] (
echo ERROR: Missing Required Paramater directory path.
goto :eof
)
if [%2] EQU [] (
echo ERROR: Missing Required Paramater, number of files to preserve
goto :eof
)
if %2 LSS 0 (
echo ERROR: Number of files to preserve provided was negative
goto :eof
)
set FolderPath=%1
set SafeNumber=%2
cd %FolderPath%
for /f %%f in ('dir /O-D /A-D /B') do call :delete %%f
goto :eof
:delete
if %SafeNumber% LEQ 0 (
del %1
) else (
set /a SafeNumber-=1
)
goto :eof
:eof
Essentially what I have here is a dir that outputs a list of filenames ordered from newest to oldest. Depending on what SafeNumber is, it will skip the first few files and then procede with deletion once SafeNumber <= 0.
The problem I'm having right now, is if the filename is "Test File.txt" (as in contains a space. "Test" is passed into the delete as %1, rather then "Test File.txt".
Any ideas on how to get my script working, or perhaps someone has a better written solution?
Solution
Have you tried putting quotation marks around the file name in your input, or in your script? I mean around the %f or the %1, for the script.
OTHER TIPS
To handle whitespace in filenames,etc. You'll want to quote for filenames and paths "%1" etc.... Maybe that is your only problem.
your going to have to use the find command with -newer and then -exec rm. For example to delete all file newer than file.txt do:
find . -type f -newer file.txt -exec rm {} \;
Long time ago, I wrote a simple Java prog that is supposed to be launched from the console, i.e. from a batch file. The prog deletes the old files from a specified directory. Check it out here, I actually don't remember how exactly it works, but I would suggest using it first on a test-folder. It is supposed to be used for Windows, at least there it is where I used it.
I now switched to a Mac, where I'm using the following Automator script I launch on each boot for doing that job:
find /Users/<yourUser>/Downloads/* -type f -mtime +90 -exec mv -f {} /Users/<yourUser>/.Trash \;
Change your for loop, and do away with your delete function.
for /f "skip=%safenum%" %%f in ('dir /o-d /a-d /b') do ( del %%f )
I have an unhealthy love of for loops...