How-to: Delete files based on their Last Modified Date

Delete files and folders older than N days:

# Delolder.ps1
# Syntax: DelOlder path_to_files Days

param( [string] $Folder, [int] $days)

"Delete from folder:$Folder items older than $days days"

if (test-path $Folder)
{
   Get-ChildItem -recurse $Folder | Where-Object {
      $_.LastWriteTime -lt (get-date).AddDays(-$days)
   } | del -recurse -whatif
  # To delete for real, remove -whatif in the line above
} 

For instructions of how to download and run this script see: Run a PowerShell script.

Examples

Assuming Delolder.ps1 is saved in the current directory:

PS C:\> ./DelOlder.ps1 "F:\work\" 90

“The possession of knowledge does not kill the sense of wonder and mystery. There is always more mystery” ~ Anais Nin

Related PowerShell Cmdlets

DelOlder.cmd - Delete files older than N days.


 
Copyright © 1999-2024 SS64.com
Some rights reserved