Want to delete only files with specific extension older than 15 days

Hi All,
I want to remove all files (only files in recurse manner not any directory) with specific file extension from location using powershell script which are older than certain number of time.

Regards
Akash R.

Hi Akash,

give a try to this oneliner, which retrieves all the files with .ico extension (change this to suit your needs), which are older than today’s date minus 15 days, then deletes them.

get-childitem -recurse -Include *.ico | where LastWriteTime -le ((date)±15d) | remove-item

hope this helps

Carlo

Be very careful using 15d or similar - if I remember correctly just happens to work. There isn’t a corresponding abbreviation for month or years
You would aslo pick up folders with this so add a -File parameter

Get-ChildItem -Path c:\temp -Filter *.xml -Recurse -File | where LastWriteTime -le (Get-Date).AddDays(-15) | Remove-Item -Force

You can alias this down a bit

ls c:\temp -Fi *.xml -R -File | ? LastWriteTime -le (Get-Date).AddDays(-15) | del -Fo -Wh

Thanks for the update for the -File parameter, Richard.
Concerning -15d, personally I like those kind of accelerators, they make using Powershell fun.
Carlo

The problem is that 15d isn’t an accelerator for days - I tripped over this a couple of years back a queried the powershell team about it. If I remember the answer d is actually decimal and just happens to work in this situation

£> 15d | gm

TypeName: System.Decimal

Ok, now I see your point.
Thanks for the explanation.

Thanks a lot everyone, Here i’ve written below and worked for me successfully:-

set folder path

$dump_path = “C:\temp\test”

set min age of files

$max_age = “-15”

get the current date

$curr_date = Get-Date

determine how far back we go based on current date

$del_date = $curr_date.AddDays($max_age)

delete only .xml files which are older than 15 days

Get-ChildItem -include *.xml $dump_path -Recurse | Where-Object { $.LastWriteTime -lt $del_date } |Where-Object { -not ($.psiscontainer) } | Foreach-Object {Remove-Item $_.FullName}

Akash, what version of Powershell are you working with?