Delete files and folders older than…

Here is a little PowerShell script  that will delete all files and folders (and all the subdirectories and files) that have the created and last modified times older than $olderthan days. You just need to change the following:

$path – specify the path where the script will search.
$olderthan – number of days you want the files and folders to be kept on the server.

You can change the days in hours, minutes,months and even years. All you have to do is change “adddays” with what you need. Example: “addminutes”,”addyears”, etc.

#Delete files older then specified days
#Version 0.1
#Created by nraddan@yahoo.com

$path="F:\Shared"
$olderthan=14
$olderdate = (get-date).adddays(-$olderthan)
$FilteredList = Get-ChildItem $path -force -recurse | where { ($_.lastwritetime -le $olderdate) -and ($_.creationtime -le 

$olderdate) }

if ($FilteredList.count -ne 0) {
#remove files older then $olderthan days
    $FilteredList | where { $_.Length -ne $null } | % {
        $creation=(get-date) - $_.creationtime
        $modified=(get-date) - $_.lastwritetime
        write-host Deleting file $_.PSPath ! "( $creation - $modified )"
        remove-item $_.PSPath -Force
        }
#remove folders older then $olderthan days
    $FilteredList | where { $_.Length -eq $null } | % {
        $creation=(get-date) - $_.creationtime
        $modified=(get-date) - $_.lastwritetime
        write-host Deleting file $_.PSPath ! "( $creation - $modified )"
        remove-item $_.PSPath -Force
        }
}

The script was test on Windows 2008 R2 Standard.

Leave a Reply

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