PowerShell: Delete files after a number of days

I used to do a lot of “batch commands” back in the good old MS-DOS days. As with everything, technology advances and PowerShell is nothing short of amazing. Support for PowerShell  commandlets seems to pop up all over the place and I use it more and more to complete tasks.

Let’s say that you want to delete files from a folder, recursively, that have a creation date before a specific number of days.  How would you do it?  That’s right – PowerShell.

$path = 'F:\Program Files\Microsoft SQL Server\MSSQL12.SQLSERVER\MSSQL\Backup\Log'
$cutoffdays = (Get-Date).AddDays(-2)

Get-ChildItem $path -Recurse | ? {
-not $_.PSIsContainer -and $_.CreationTime -lt $cutoffdays
} | Remove-Item

You can even look for files that have a specific extension:

$path = 'F:\Program Files\Microsoft SQL Server\MSSQL12.SQLSERVER\MSSQL\Backup\Log'
$cutoffdays = (Get-Date).AddDays(-2)
$extension = '.trn'

Get-ChildItem $path -Recurse | ? {
-not $_.PSIsContainer -and $_.CreationTime -lt $cutoffdays -and $_.Extension -ieq $extension
} | Remove-Item

There are a number of other parameters and options. Give it a shot.

Leave a Comment