Let’s explore an example that demonstrates how PowerShell can efficiently remove files older than a specified date, offering a practical solution for file cleanup.
Delete Files in Folder Older than a Date
This script offers a solution for managing file cleanup based on your specified date. You’ll need to amend those variables at the top of the script.
# Script 1: Delete files older than a specified date $folder = "D:\mssql" $maxAge = 30 $cutoffDate = (Get-Date).AddDays(-$maxAge) $filesToDelete = Get-ChildItem $folder | Where-Object { $_.LastWriteTime -lt $cutoffDate } $filesToDelete | Remove-Item # Script 2: Delete all .txt files in the folder & subfolders $path = "C:\temp\demoFolder" if (Test-Path $path) { Get-ChildItem $path -Include *.txt -Recurse | Remove-Item }
This script operates by deleting files within the specified folder (includes subfolders), with a last write time older than 30 days from the current date. The flexibility lies in your ability to tailor the behavior of the script by adjusting the $maxAge
and $folder
variables according to your specific requirements.
A word of caution: This script does not transfer deleted files to the recycle bin. Exercise caution to prevent unintentional deletion of important files. It is advisable to conduct a trial run on a small, non-critical folder before applying it to a larger directory or system.