How to delete files by age with PowerShell

You can easily use PowerShell to delete files that are older than x minutes/hours/days.  This is useful if you have a temporary folder which you would like to regularly clear down.  Please see the below examples:

Delete files older than x minutes

Get-ChildItem -path C:\temp | where {$_.Lastwritetime -lt (date).addminutes(-5)} | remove-item

Delete files older than x hours

Get-ChildItem -path C:\temp | where {$_.Lastwritetime -lt (date).addhours(-2)} | remove-item

Delete files older than x days

Get-ChildItem -path C:\temp | where {$_.Lastwritetime -lt (date).adddays(-30)} | remove-item

 

Be the first to comment

Leave a Reply

Your email address will not be published.


*