How do I delete old files from a directory while keeping the most recent ones on Windows [duplicate]

随声附和 提交于 2019-11-28 11:34:24
subha

exact syntax: FORFILES /p d:\new /d -30 /m * /c "cmd /c del @file"

The simplest way would be a .bat run file run weekly or monthly.

cd \mylog\dir
mkdir archive
del /Q .\archive\*.log
move *.log .\archive

If you want something more complex look into downloading the cygwin tools to use un*x like commands, or possibly look into Powershell.

With VBScript, adapted from ScriptingAnswers

Dim fso, startFolder, OlderThanDate
Set fso = CreateObject("Scripting.FileSystemObject")

startFolder = "E:\temp"           ' folder to start deleting (subfolders will also be cleaned)

OlderThanDate = DateAdd("d", -07, Date)  ' 07 days (adjust as necessary)

DeleteOldFiles startFolder, OlderThanDate

Function DeleteOldFiles(folderName, BeforeDate)
    Dim folder, file, fileCollection, folderCollection, subFolder

    Set folder = fso.GetFolder(folderName)

    Set fileCollection = folder.Files

    For Each file In fileCollection
        If file.DateLastModified < BeforeDate Then
            ' fso.DeleteFile(file.Path)    # Modify this to delete after testing
            WScript.StdOut.WriteLine (file.Path)
        End If
    Next

    Set folderCollection = folder.SubFolders
    For Each subFolder In folderCollection
        DeleteOldFiles subFolder.Path, BeforeDate
    Next

End Function

You can run this script with CScript

@Jason: nice utility, FORFILES from the Resource Kit

Schedule a batch file to handle this.

This line will delete all files (*.*) in c:\mydirectory that are older than 14 days:

FORFILES -pc:\mydirectory -s -m*.* -d-14 -c"DEL @FILE"

Put that in a text file, rename it to something like "deletefiles.bat" and schedule it.

I haven't tested this, but should be easy enough to try.


EDIT: If you use this, make sure you understand what is happening - the -s flag tells it to recurse the subdirectories, and that may not be what you want to happen. Also, you may need to specify some flags for the DEL command too. :)


EDIT: Realized that you need to download stuff from Microsoft in order for FORFILES to work. I like the accepted solution too, since you don't have to have anything special. The only problem is that it only happens every two weeks instead of running a process daily to remove all things older than 14 days. For what that's worth. :P

Why dont you write a batch file or a powershell script and schedule it?

Script for deleting files older than a specified date.

It's fairly trivial to do if you have a perl (or similar) installed on the server:

#!perl
foreach my $file (</path/to/logs/*.log>) {
  next unless -M $file > 14;
  print "Deleting $file...\n";
  # unlink $file or die "Failed to remove $file: $!";
}

The line that actually does the delete is commented out, since there might be kids in the house :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!