Delete Files Older Than in PowerShell

Here is an example of how to use PowerShell to delete files older than a specified date:

# Set the path to the folder containing the files you want to delete
$folder = "C:\myfolder"

# Set the maximum age of the files in days
$maxAge = 30

# Get the current date and subtract the maximum age to get the cutoff date
$cutoffDate = (Get-Date).AddDays(-$maxAge)

# Get all the files in the folder that are older than the cutoff date
$files = Get-ChildItem $folder | Where-Object { $_.LastWriteTime -lt $cutoffDate }

# Delete the files
$files | Remove-Item

This script will delete all files in the specified folder that have the last write time older than 30 days from the current date. You can adjust the $maxAge and $folder variables to customize the behaviour of the script.

Note that this script does not move the deleted files to the recycle bin, so be careful when using it to avoid accidentally deleting important files. It’s always a good idea to test the script on a small, non-critical folder before running it on a larger folder or system.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *