- December 4, 2017
- Posted by: Syed Shujaat
- Category: Uncategorized
Automatically Delete Files/Folders older than a certain number of days.
You can create a batch file with the following command line.
forfiles -p “C:\Test” -s -m *.* /D -5 /C “cmd /c del @path”
Basically, it tells Windows to delete all files in the C:\Test folder and sub-folders that are older than 5 days.
Next Step is to schedule your task. Scroll down to the Schedule Batch File on PC Startup section and follow along.
The only thing you have to change is the Trigger. You can choose from Daily, Weekly, Monthly, When the computer starts, When I log on or When a specific event is logged.
When you pick something like Weekly or Monthly and click Next, you’ll get a new screen where you can configure the exact time and days you want the script to run.
Hopefully, this is a good solution for most people who need to perform some simple automated tasks for deleting files on their PCs.
PowerShell Script:
This is a simple Powershell script which deletes Files older than some days. You can use it to cleanup old logfiles or other things. If you run the script the first time you can add the “-WhatIf” parameter after Remove-Item command.
# Delete all Files in C:\temp older than 30 day(s)
$Path = “C:\temp”
$Daysback = “-30”
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item
|
—————————————————————————————————————————————-
If you need to delete files in subfolders too, you can use this script. This is the same script with the Get-Childitem parameter “-Recurse”.
# Delete all Files in C:\temp older than 30 day(s)
$Path = “C:\temp”
$Daysback = “-30”
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path -Recurse ( | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item
|
——————————————————————————————————————————————————–
Leave a Reply
You must be logged in to post a comment.