Answer the question
In order to leave comments, you need to log in
Script to delete files before a specific hour on Windows?
There was a need to delete files that are formed within an hour. There are examples that delete "after a certain time", but "until a certain time" was never found. How to write a script that deletes files (.xlsx for example) created no later than one hour? Interested in a variant that works on standard Windows tools.
Answer the question
In order to leave comments, you need to log in
Good afternoon!
As an option, use Powershell, but set the reverse filtering in the check condition, not "older" from the current date, but "newer".
Yes, it's done in one line.
Example:
Get-ChildItem c:\inetpub\logs\LogFiles\ -Recurse -Filter *.log | Where-Object {$_.LastWriteTime -lt [datetime]::Today.AddMonths(-1)} | Remove-Item
Yesterday I answered a similar question, but yours is a bit more complicated.
Using a batch file (cmd), you can do this like this: You can
get a list of files sorted in reverse order by file modification time using the command: You can
calculate the time one hour ago using the built-in variable %TIME%, which returns the current time. Variable %DATE% - returns the current date. Don't forget the change of day option. cmd does not know how to work with date and time, you will have to write all the arithmetic with date / time yourself (select minutes and hours from% TIME% and perform arithmetic operations with them). Here we must also take into account that numbers starting with 0 are octal for cmd and the fact that the data format in %DATE% and %TIME% (and in dir output) depends on the settings of the current OS locale.
The output of dir will be the time and date, compare it with the current date and the calculated time, and delete the file if necessary. Because files will be sorted in reverse order by date / time, then after the first file that does not satisfy the condition, processing can be completed.
Help:
dir /?
for /? (your version of for /f)
set /? (for arithmetic: set /a)
Selection of a substring from a variable is described in set /?
In general, everything can be implemented, but calculating the date / time one hour ago may not be a trivial task, given the transition of the day (as well as the transition of the date - days, months and years).
So, I think it's better to prefer the PoSh option.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question