0

I need to delete files in an specific folder with a batch script, however, I need to keep the last file generated. Our server has an IIS folder that keeps generating logs, and we need to keep always the last one, but delete the older ones.

Currently we have this script that deletes all the files in an specific folder (in this case, all the files inside C:\Temp):

del /q "C:\Temp\*"
FOR /D %%p IN ("C:\Temp\*.*") DO rmdir "%%p" /s /q

How could we edit that code to keep the last file generated in the folder?

Thank you in advance for your help.

Fabián Cerda
  • 21
  • 1
  • 1
  • 2
  • Look for the newest file and delete all the ones that are not that file? – Tyler Nichols Sep 25 '17 at 15:28
  • You need to search, research, write and try code yourself. Posting a file that doesn't even attempt to perform the task you need and asking for it to be added is a direct code request and is off topic here. – Compo Sep 25 '17 at 15:30
  • You say you want to delete files, so using `rmdir` makes no sense as it deletes directories... – aschipfl Sep 25 '17 at 16:31

1 Answers1

0

This batch file offers one solution:

@echo off
set "SourceFolder=C:\Temp"
for /F "skip=1 delims=" %%I in ('dir "%SourceFolder%\*" /A-D /B /O-D 2^>nul') do del "%SourceFolder%\%%I"
set "SourceFolder="

The command DIR outputs a list of just file names because of the options /A-D (directory entries with directory attribute not set) and /B (bare format) ordered reverse by last modification date because of /O-D which means the name of the newest modified file is output first.

An error message output by DIR if the specified folder does not contain any file is suppressed by redirecting the error message written to handle STDERR to device NUL using 2>nul. The redirection operator > must be escaped here with caret character ^ to be interpreted as literal character on processing the entire FOR command line by Windows command interpreter. Later FOR executes in a separate command process in background the command dir "%SourceFolder%\*" /A-D /B /O-D 2>nul and captures the output written to STDOUT.

FOR option skip=1 results in skipping first line of captured output which means ignoring the file name of newest modified file.

FOR option delims= disables the default splitting up of the captured lines into space/tab separated strings as every entire file name should be assigned to loop variable I for usage by command executed by FOR.

DEL deletes the file if that is possible at all.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • del /?
  • dir /?
  • echo /?
  • for /?
  • set /?

Read also the Microsoft article about Using Command Redirection Operators.

Mofi
  • 46,139
  • 17
  • 80
  • 143