berks123
berks123

Reputation: 11

Using a batch file, how do I delete large, old files?

I have temp files which are taking up a lot of disk space which I want to tidy on a scheduled basis using a batch file.

The file names I want to deal with always start with "harp_" but I want to keep the most recent 2 files.

For example the folder contains files such as:

I want the folder to just now contain:

Is anyone able to help me script the batch file for this?

Upvotes: 0

Views: 168

Answers (2)

user6811411
user6811411

Reputation:

I'm quite unsure if batch to bash is required. In case of batch my answer is like Squashman's adding an aspect of security, files to be deleted are added to a tmp-file which might be revised edited before execution.

@Echo off&Setlocal
Set Basefldr=C:\where\ever
PushD "%Basefldr%" ||(Echo Couldn't cd to %Basefldr% &Pause&Exit /B 1)
Set DelList="%tmp%\DelList.cmd"
Type NUL>%DelList%
For /f "skip=2 delims=" %%A in ('Dir /B/A-D/O-D "harp_*"'
  ) Do >>%DelList% Echo:Del %%~fA
:: Review the file DelList.cmd before executing it
Notepad.exe %DelList%
:: or
::   more %DelList%
popd

Upvotes: 1

Squashman
Squashman

Reputation: 14290

You can use the FOR /F command to parse the output of the DIR command. The key is using the SKIP option so that it keeps the two newest files.

FOR /F "skip=2 delims=" %%G IN ('DIR /A-D /B /O-D harp_*') DO del "%%~G"

Upvotes: 2

Related Questions