PowerShell – Find & Remove Files/Folders Older Than X Days


Ever wanted to purge all files and folders based on their creation date?. In my work environment we wanted to do just that, and depending on the location we needed to specify different retention lengths hence the following simple but effective PS script:

$dir = "\\FILESERVER\SHARETOINSPECT\"
$day = "365"
Get-ChildItem -Path $dir | Where-Object {$_.PSIsContainer -eq $true -and $_.CreationTime -lt (get-date).adddays(-$day)} | Remove-Item -Recurse -Force -Verbose

In the above example I have specified 365 days as the variable, however you can modify this using years, hours etc. Running the above script will result in all files and folders with creation dates older than the specified max being purged from the system.

As always use with caution and ensure you have backups.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s