Windows PowerShell - Recursively delete files and directories modified more than ‘n’ days ago.

I was recently tasked with writing a script that recursively deletes files and directories modified more than ‘n’ days ago - here’s the kicker - using Windows. Many people have accomplished this with long VB Scripts. I was hoping for a much cleaner solution, and decided to try Windows PowerShell . I am quite impressed with Windows Powershell’s capabilities.

The following script recursively deletes files and directories modified more than 16 days ago.

# prune.ps1
$sticky = (Get-date).AddDays(-16)
$backupDir = "B:\backup"
echo "Recursively deleting files and directories written before $sticky"
Get-ChildItem $backupDir -Recurse | Where-Object { $_.LastWriteTime -lt $sticky } | Remove-Item -Recurse

Note that you can change Remove-Item -Recurse to Remove-Item -Whatif to “pretend” to delete files, and display potential deletes on STDOUT. You can also specify Remove-Item -Confirm.

I created a scheduled task that runs a .bat file containing the following:
powershell.exe c:\scripts\prune.ps1 >> c:\scripts\logs\prune.log

To watch and or view the output of the script, specify the -noexit switch on the command line.
powershell.exe -noexit c:\scripts\prune.ps1

Tags: , ,

Leave a Reply