K
K
Kastrulya00012014-08-14 19:08:06
cmd/bat
Kastrulya0001, 2014-08-14 19:08:06

How to write a script (.bat) to delete files except the last one?

Baki, which the server raises, fall into the folder once an hour, and you need a script that would clean up all the files in the folder, except for the last one. The last thing that succeeded was a script that cleans everything older than one day, but this is no good, you need to leave only one file, at least for the last 2 hours. Here is the script:

@ECHO OFF
REM Удаляем файлы (@isdir==FALSE) старше одного дня (-d -1)
FORFILES -p "D:\AutoBackup" -s -m * -d -1 -c "CMD /C if @isdir==FALSE DEL /f /q @path"
EXIT /B 0

Specifying a time multiple of an hour does not work there, so I'm looking for another solution.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew, 2014-08-14
@OLS

At the first step, run FOR or FORFILES sorted by ascending file modification time; in the body of this FOR, assign the found name to some variable.
After passing through the first loop, the variable will contain the name of the last file.
In the second step, run FOR or FORFILES on all files; in the body of this FOR, delete all files if their name does not match the result variable from the first step.

K
Kastrulya0001, 2014-09-02
@Kastrulya0001

As a result, a vbs script was created that performs this procedure, the start time was registered in the Windows scheduler.
I am attaching the code, it will probably come in handy for someone, in the first line you need to register your folder that needs to be cleared:

WorkDir="D:\AutoBackup"
set fso = createobject("scripting.filesystemobject")  
set sha = createobject("shell.application")  
set dir = sha.namespace(WorkDir)  

' Определяем файл с максимальной датой
set arr = dir.items  
arr.filter 192, "*.bak"  
for i = 0 to arr.count - 1  
   if i = 0 then
      set fnewest = fso.getfile(arr.item(i).path)
   else
      if fnewest.datecreated < fso.getfile(arr.item(i).path).datecreated then  
         set fnewest = fso.getfile(arr.item(i).path)  		'получаем последний полный бэкап
      end if  
   end if  
next

''''''''''''''''''''''''''''''''''

' Удаляем файлы, кроме последнего
Set filesys = CreateObject("Scripting.FileSystemObject")
Set objFolder = filesys.GetFolder(WorkDir)
For Each File in objFolder.Files

'If LCase(filesys.GetExtensionName(File)) = "bak" AND _
'DateDiff("D", File.DateLastModified, Now) > 7 Then
'File.Delete true
'End If
If fnewest = File Then
  d1 = File.Name
  'MsgBox "Последний файл: " &d1
else
  d2 = File.Name
  File.Delete true
end if

Next

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question