I wonder if .bat support to delete files older than N hours? I have a script that removes files older than N days but couldn't find command to remove based on hours. If the .bat file doesn't have the hourly function, can we do this using PowerShell script? I am trying to clean up all the files in C:\temp (Windows Server) that are older than 6 hours.
Asked
Active
Viewed 6,013 times
2 Answers
0
You can definitely get these informations using powershell easily enough.
You would need to use Get-ChildItem (with recurse parameter) and filter out folders.
get-childitem 'C:\Temp' | Where-Object PSIsContainer -eq $false
See the script below for a base to get started.
$Files = get-childitem 'C:\Temp' | Where-Object PSIsContainer -eq $false
$LimitTime = (Get-Date).AddHours(-6)
$Files | ForEach-Object {
if ($_.CreationTime -lt $LimitTime -and $_.LastWriteTime -lt $LimitTime) {
Remove-Item -Path $_.FullName -Force -WhatIf
}
}
To note You will need to remove the -WhatIf for this script to actually delete anything.
Edit:
Thanks to andyb comment, i removed the timespan in favor for a direct date comparison.

Sage Pourpre
- 9,932
- 3
- 27
- 39
-
1No need for a TimeSpan; just use `(Get-Date).AddHours(-6)` – andyb Sep 07 '17 at 02:20
-
Silly me, I improved my answer with your suggestion. – Sage Pourpre Sep 07 '17 at 02:27
0
Very hard in traditional batch file, but almost trivial in PowerShell. You can determine the date & time '6 hours ago' by simply adding -6 hours to the object returned by Get-Date
. After that, it's just a question if finding the files and comparing the LastWriteTime
property to (get-date).AddHours(-6)
and piping the results to remove-item
.
get-childitem -path <path> |
where-object { -not $_.PSIsContainer -and ( $_.LastWriteTime -lt (Get-Date).AddHours(-6) ) } |
remove-item -force

andyb
- 2,722
- 1
- 18
- 17
-
Adding the CreationTime in that check can be a good thing too. The LastWriteTime won't be updated if a file is moved/copied over a folder. I had files with creationTime date set to september 2017 (I moved them) while their LastWriteTime was dated from 2004. – Sage Pourpre Sep 07 '17 at 02:41
-
It's good to understand the difference between Creation Time and Last Write Time, but in this instance, I don't think they are both needed. The question is about clearing out files from a temp folder; I can't imagine I'd ever move old files into a temp folder that I knew was being automatically cleaned. Particularly not if those files had much value. – andyb Sep 07 '17 at 02:56
-
Spare a thought for those poor folks in *nix land where they have to contend with Last Accessed, Last Modified and Last Changed timestamps! – andyb Sep 07 '17 at 03:01