Powershell – How to delete files and folders older than a date

Ok. so this seems pretty simple but sometimes can be daunting figuring out how to actually delete files and folders (recursively). In the script below, all you need to do is define the variables for the directory and how old do you want to go back. Simply change the $directory and $OlderThan variables and kick the script off. Actually, I’ve got a line commented out for you to run this script in “WhatIf” mode. In WhatIf mode, the script simply tells you what it would do if you ran it. Pretty cool!

# Delete items older than a date including subfolders
$directory = 'e:\path\to\what\you\want\to\delete' 
$OlderThan = 365
# To do a Whatif: Get-ChildItem $directory | Where-Object {$_.CreationTime -le (Get-Date).AddDays(-$OlderThan)} | Foreach-Object { Remove-Item $_.FullName -Recurse -Verbose -Force -whatif}
Get-ChildItem $directory | Where-Object {$_.CreationTime -le (Get-Date).AddDays(-$OlderThan)} | Foreach-Object { Remove-Item $_.FullName -Recurse -Verbose -Force}

Leave a Reply

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