- Powershell Forfiles Command
- Forfiles Windows 10 64
- Forfiles Windows 2012
- Forfiles Access Denied Windows 10
Active1 month ago
I am looking for a way to delete all files older than 7 days in a batch file. I've searched around the web, and found some examples with hundreds of lines of code, and others that required installing extra command line utilities to accomplish the task.
Similar things can be done in BASH in just a couple lines of code. It seems that something at least remotely easy could be done for batch files in Windows. I'm looking for a solution that works in a standard Windows command prompt, without any extra utilities. Please no PowerShell or Cygwin either.
On Windows 10, the process to rename a single file is easy, but it can quickly become troublesome when trying to change the name (or extension) to a long list of files within a folder. May 22, 2018 The forfiles command was first introduced as an optional component of Windows NT. Beginning with Windows Vista, it was included in the standard Windows operating system. It's also available as part of Windows 7, Windows 8, and Windows 10.
Powershell Forfiles Command
Stephan39.3k55 gold badges3535 silver badges6464 bronze badges
With forfiles, you can run a command on or pass arguments to multiple files. For example, you could run the type command on all files in a tree with the.txt file name extension. Or you could execute every batch file (.bat) on drive C, with the file name 'Myinput.txt' as the first argument. Forfiles Forfiles is a useful windows command to select a set of files and then run a command on each of the files. It’s similar to the functionality of find command on Linux OS. The syntax of the forfiles is as follows.
KibbeeKibbee52.6k2626 gold badges134134 silver badges173173 bronze badges
23 Answers
Enjoy:
See
forfiles
documentation for more details.For more goodies, refer to An A-Z Index of the Windows XP command line.
If you don't have
forfiles
installed on your machine, copy it from any Windows Server 2003 to your Windows XP machine at %WinDir%system32
. This is possible since the EXE is fully compatible between Windows Server 2003 and Windows XP.Later versions of Windows and Windows Server have it installed by default.
For Windows 7 and newer (including Windows 10):
The syntax has changed a little. Therefore the updated command is:
FZs4,01688 gold badges1818 silver badges3232 bronze badges
akuaku104k3030 gold badges162162 silver badges199199 bronze badges
Run the following commands:
Move all the files (using /mov, which moves files and then deletes them as opposed to /move which moves whole filetrees which are then deleted) via robocopy to another location, and then execute a delete command on that path and you're all good.
Also if you have a directory with lots of data in it you can use
David Tonhofer/mir
switch 6,11111 gold badge3737 silver badges3333 bronze badges
ImanIman
Ok was bored a bit and came up with this, which contains my version of a poor man's Linux epoch replacement limited for daily usage (no time retention):
7daysclean.cmd
USAGE
set /a strip=day*7
: Change 7 for the number of days to keep.set dSource=C:temp
: This is the starting directory to check for files.NOTES
This is non-destructive code, it will display what would have happened.
Change :
to something like :
so files actually get deleted
February: is hard-coded to 28 days. Bissextile years is a hell to add, really. if someone has an idea that would not add 10 lines of code, go ahead and post so I add it to my code.
epoch: I did not take time into consideration, as the need is to delete files older than a certain date, taking hours/minutes would have deleted files from a day that was meant for keeping.
LIMITATION
epoch takes for granted your short date format is YYYY-MM-DD. It would need to be adapted for other settings or a run-time evaluation (read sShortTime, user-bound configuration, configure proper field order in a filter and use the filter to extract the correct data from the argument).
Did I mention I hate this editor's auto-formating? it removes the blank lines and the copy-paste is a hell.
I hope this helps.
aphoria16.6k66 gold badges5252 silver badges6464 bronze badges
JayJay
You should do
Sathyajith Bhat/d -3
(3 days earlier) This works fine for me. So all the complicated batches could be in the trash bin. Also forfiles
don't support UNC paths, so make a network connection to a specific drive.16.9k2121 gold badges8686 silver badges121121 bronze badges
Arno JansenArno Jansen
Have a look at my answer to a similar question:
This deletes files older than a given date. I'm sure it can be modified to go back seven days from the current date.
update: I notice that HerbCSO has improved on the above script. I recommend using his version instead.
Community♦
e.Jamese.James84.7k3333 gold badges163163 silver badges206206 bronze badges
My command is
@PATH
- is just path in my case, so I had to use @PATH@FILE
also
forfiles /?
not working for me too, but forfiles
(without '?') worked fine.And the only question I have: how to add multiple mask (for example '.log|.bak')?
All this regarding forfiles.exe that I downloaded here (on win XP)
But if you are using Windows server forfiles.exe should be already there and it is differs from ftp version. That is why I should modify command.
For Windows Server 2003 I'm using this command:
Sathyajith Bhat16.9k2121 gold badges8686 silver badges121121 bronze badges
segerosegero
For Windows Server 2008 R2:
This will delete all .sql files older than 90 days.
NotJustClarkKentNotJustClarkKent
Use forfiles.
There are different versions. Early ones use unix style parameters.
My version (for server 2000 - note no space after switches)-
To add forfiles to XP, get the exe from ftp://ftp.microsoft.com/ResKit/y2kfix/x86/
and add it to C:WINDOWSsystem32
Aidan EwenAidan Ewen9,21744 gold badges5151 silver badges7171 bronze badges
For windows 2012 R2 the following would work:
to see the files which will be deleted use this
Viktor KaViktor Ka
There are very often relative date/time related questions to solve with batch file. But command line interpreter cmd.exe has no function for date/time calculations. Lots of good working solutions using additional console applications or scripts have been posted already here, on other pages of Stack Overflow and on other websites.
Common for operations based on date/time is the requirement to convert a date/time string to seconds since a determined day. Very common is 1970-01-01 00:00:00 UTC. But any later day could be also used depending on the date range required to support for a specific task.
Jay posted 7daysclean.cmd containing a fast 'date to seconds' solution for command line interpreter cmd.exe. But it does not take leap years correct into account. J.R. posted an add-on for taking leap day in current year into account, but ignoring the other leap years since base year, i.e. since 1970.
I use since 20 years static tables (arrays) created once with a small C function for quickly getting the number of days including leap days from 1970-01-01 in date/time conversion functions in my applications written in C/C++.
This very fast table method can be used also in batch code using FOR command. So I decided to code the batch subroutine
GetSeconds
which calculates the number of seconds since 1970-01-01 00:00:00 UTC for a date/time string passed to this routine.Note: Leap seconds are not taken into account as the Windows file systems also do not support leap seconds.
First, the tables:
- Days since 1970-01-01 00:00:00 UTC for each year including leap days.Calculating the seconds for year 2039 to 2106 with epoch beginning 1970-01-01 is only possible with using an unsigned 32-bit variable, i.e. unsigned long (or unsigned int) in C/C++.But cmd.exe use for mathematical expressions a signed 32-bit variable. Therefore the maximum value is 2147483647 (0x7FFFFFFF) which is 2038-01-19 03:14:07.
- Leap year information (No/Yes) for the years 1970 to 2106.
- Number of days to first day of each month in current year.
Converting a date to number of seconds since 1970-01-01 is quite easy using those tables.
Attention please!
The format of date and time strings depends on Windows region and language settings. The delimiters and the order of tokens assigned to the environment variables
Day
, Month
and Year
in first FOR loop of GetSeconds
must be adapted to local date/time format if necessary.It is necessary to adapt the date string of the environment variable if date format in environment variable DATE is different to date format used by command FOR on
%%~tF
.For example when
%DATE%
expands to Sun 02/08/2015
while %%~tF
expands to 02/08/2015 07:38 PM
the code below can be used with modifying line 4 to:This results in passing to subroutine just
02/08/2015
- the date string without the 3 letters of weekday abbreviation and the separating space character.Alternatively following could be used to pass current date in correct format:
Now the last 10 characters from date string are passed to function
GetSeconds
and therefore it does not matter if date string of environment variable DATE is with or without weekday as long as day and month are always with 2 digits in expected order, i.e. in format dd/mm/yyyy
or dd.mm.yyyy
.Here is the batch code with explaining comments which just outputs which file to delete and which file to keep in
C:Temp
folder tree, see code of first FOR loop.For optimal performance it would be best to remove all comments, i.e. all lines starting with rem after 0-4 leading spaces.
And the arrays can be made also smaller, i.e. decreasing the time range from 1980-01-01 00:00:00 to 2038-01-19 03:14:07 as currently supported by the batch code above for example to 2015-01-01 to 2019-12-31 as the code below uses which really deletes files older than 7 days in
C:Temp
folder tree.Further the batch code below is optimized for 24 hours time format.
For even more information about date and time formats and file time comparisons on Windows see my answer on Find out if file is older than 4 hours in batch file with lots of additional information about file times.
Community♦
MofiMofiForfiles Windows 10 64
31.4k88 gold badges4242 silver badges9191 bronze badges
Copy this code and save it as
DelOldFiles.vbs
.USAGE IN CMD :
cscript //nologo DelOldFiles.vbs 15
15 means to delete files older than 15 days in past.
ParisParis
IMO, JavaScript is gradually becoming a universal scripting standard: it is probably available in more products than any other scripting language (in Windows, it is available using the Windows Scripting Host). I have to clean out old files in lots of folders, so here is a JavaScript function to do that:
For each folder to clear, just add another call to the clearFolder() function. This particular code also preserves exe and dll files, and cleans up subfolders as well.
Graham LaightGraham Laight3,23733 gold badges2020 silver badges2222 bronze badges
How about this modification on 7daysclean.cmd to take a leap year into account?
It can be done in less than 10 lines of coding!
Edit by Mofi:
The condition above contributed by J.R. evaluates always to false because of invalid syntax.
And
Month GEQ 2
is also wrong because adding 86400 seconds for one more day must be done in a leap year only for the months March to December, but not for February.A working code to take leap day into account - in current year only - in batch file 7daysclean.cmd posted by Jay would be:
Community♦
J.R.J.R.
Might I add a humble contribution to this already valuable thread. I'm finding that other solutions might get rid of the actual error text but are ignoring the %ERRORLEVEL% which signals a fail in my application. AND I legitimately want %ERRORLEVEL% just as long as it isn't the 'No files found' error.
Some Examples:
Debugging and eliminating the error specifically:
Using a oneliner to return ERRORLEVEL success or failure:
Using a oneliner to keep the ERRORLEVEL at zero for success within the context of a batchfile in the midst of other code (ver > nul resets the ERRORLEVEL):
For a SQL Server Agent CmdExec job step I landed on the following. I don't know if it's a bug, but the CmdExec within the step only recognizes the first line of code:
StingSting
If you have the XP resource kit, you can use robocopy to move all the old directories into a single directory, then use rmdir to delete just that one:
neuracnuneuracnu
I think e.James's answer is good since it works with unmodified versions of Windows as early as Windows 2000 SP4 (and possibly earlier), but it required writing to an external file. Here is a modified version that does not create an external text file while maintaining the compatibility:
To be true to the original question, here it is in a script that does ALL the math for you if you call it with the number of days as the parameter:
NOTE: The code above takes into account leap years, as well as the exact number of days in each month. The only maximum is the total number of days there have been since 0/0/0 (after that it returns negative years).
NOTE: The math only goes one way; it cannot correctly get future dates from negative input (it will try, but will likely go past the last day of the month).
Community♦
LectrodeLectrode
Gosh, a lot of answers already. A simple and convenient route I found was to execute ROBOCOPY.EXE twice in sequential order from a single Windows command line instruction using the & parameter.
In this example it works by picking all files (.) that are older than 30 days old and moving them to the target folder. The second command does the same again with the addition of the PURGE command which means remove files in the target folder that don’t exist in the source folder.So essentially, the first command MOVES files and the second DELETES because they no longer exist in the source folder when the second command is invoked.
Forfiles Windows 2012
Consult ROBOCOPY's documentation and use the /L switch when testing.
It Wasn't Me67311 gold badge66 silver badges2020 bronze badges
GBGOLCGBGOLC
Forfiles Access Denied Windows 10
You might be able to pull this off. You can take a look at this question, for a simpler example. The complexity comes, when you start comparing the dates. It may be easy to tell if the date is greater or not, but there are many situations to consider if you need to actually get the difference between two dates.
In other words - don't try to invent this, unless you really can't use the third party tools.
Community♦
PauliusPaulius4,57977 gold badges3737 silver badges4545 bronze badges
this is nothing amazing, but i needed to do something like this today and run it as scheduled task etc.
batch file, DelFilesOlderThanNDays.bat below with sample exec w/ params:
DelFilesOlderThanNDays.bat 7C:dir1dir2dir3logs*.log
Goran B.Goran B.
Expanding on aku's answer, I see a lot of people asking about UNC paths. Simply mapping the unc path to a drive letter will make forfiles happy. Mapping and unmapping of drives can be done programmatically in a batch file, for example.
This will delete all files with a .gz extension that are older than 7 days. If you want to make sure Z: isn't mapped to anything else before using it you could do something simple as
Tobias JärvelövTobias Järvelöv
ROBOCOPY works great for me. Originally suggested my Iman. But instead of moving the files/folders to a temporary directory then deleting the contents of the temporary folder, move the files to the trash!!!
This is is a few lines of my backup batch file for example:
It cleans anything older than 15 days out of my 'Temp' folder and 30 days for anything in my AutoCAD backup folder. I use variables because the line can get quite long and I can reuse them for other locations. You just need to find the dos path to your recycle bin associated with your login.
This is on a work computer for me and it works. I understand that some of you may have more restrictive rights but give it a try anyway;) Search Google for explanations on the ROBOCOPY parameters.
Cheers!
Shawn PauliszynShawn Pauliszyn
This one did it for me. It works with a date and you can substract the wanted amount in years to go back in time:
the
/F
in the cmd /c del @path /F
forces the specific file to be deleted in some the cases the file can be read-only.the
SnickbrackSnickbrackdateYear
is the year Variable and there you can change the substract to your own needs46611 gold badge88 silver badges3030 bronze badges
My script to delete files older than a specific year :
efdummyefdummy
protected by Community♦Sep 7 '11 at 15:52
Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
Would you like to answer one of these unanswered questions instead?
Not the answer you're looking for? Browse other questions tagged windowsdatebatch-filefile-iocmd or ask your own question.
Active11 months ago
I'm looking to automatically delete files older than 7 days old with
forfiles
.The code below works when I do it manually and respond yes to deleting the files. How can I incorporate the yes into this?
This is the output:
Dennis42.2k88 gold badges107107 silver badges139139 bronze badges
PHLiGHTPHLiGHT27622 gold badges55 silver badges1515 bronze badges
3 Answers
You could try adding in a /Q /S, though be aware that this may not in fact do what you really want it to:
You are probably better off either using CSCRIPT (with your choice of VBScript or JScript) or PowerShell. Check out this answer from StackOverflow: https://stackoverflow.com/questions/1575493/how-to-delete-empty-subfolders-with-powershell
Here is some vbscript to accomplish a similar task:
Community♦
GoyuixGoyuix5,56133 gold badges3131 silver badges4747 bronze badges
This example removes all files in the folder 'G:db_bk_copies' older than 3 days without asking the users to confirm deletion (Are you sure (Y/N)?):
forfiles -p 'G:db_bk_copies' -s -m * /D -3 /C 'cmd /c del /a-s @path'
2,50011 gold badge1616 silver badges3333 bronze badges
Ahmed GenediAhmed Genedi
Verify that the files are not Hidden or system files.
If System try:
If Hidden Try:
DavidPostill♦115k2727 gold badges255255 silver badges285285 bronze badges
user616835user616835