Arczi10
Arczi10

Reputation: 11

Delete files older than 5 minutes using PowerShell

I would like to delete only the files (*.txt) that were created more than 5 minutes ago in a particular folder. I've try something like this but its delete all *.txt files with no exception.

$limit = (Get-Date).AddMinutes(-5)
$path = "C:\Users\akoch\Desktop\Folder1"
$Extension = "*.txt"

Get-ChildItem -Path $path -Include $Extension -Force | Where-Object {$_.CreationTime -lt $limit} | Remove-Item 

Upvotes: 1

Views: 11133

Answers (1)

Vladimir Bundalo
Vladimir Bundalo

Reputation: 655

Use -filter instead of -include

$limit = (Get-Date).AddMinutes(-5)
$path = "C:\Users\akoch\Desktop\Folder1"
$Extension = "*.txt"

Get-ChildItem -Path $path -Filter $Extension -Force | Where-Object {$_.CreationTime -lt $limit} | Remove-Item

The issue here is that you actually are not filtering anything

Upvotes: 5

Related Questions