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.

Reading Stuff

Information in this document subject to change without notice.
All Software source code published is for demonstration and knowledge sharing purposes only. The Code is supplied "as is" without warranty as to result, performance or merchantability. Use at your own risk.
The opinions expressed herein are the opinions of the author and do not reflect those of any other entity.