Delete files in a directory that are older than x number of days.
Sometimes there’s a need to delete files that are older than a certain number of days, months, or years. This is especially true when creating scheduled jobs to clean up server logs, old cached files, etc.
This simple script can be ran to do so, just edit the number of days and the targeted directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# PowerShell script to delete old files in a directory. # Script will delete files that are older (last modified) than the number of days defined. # Define number of days $timewindow = (get-date).addDays(-10) # Define directory to remove files from $directory = "C:\temp\" $getItems = Get-ChildItem -Path $directory foreach ($file in $getItems) { IF ($file.LastWriteTime -lt $timeWindow) { write-host -foregroundcolor White "File deleted:" $file.Name "("$file.LastWriteTime")" remove-item $file.FullName } } |
Once specifying the folder and number of days, this script can be ran or scheduled- perfect for clean-up tasks.