Author Posts

February 27, 2014 at 10:59 pm

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.

February 28, 2014 at 1:28 am

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

February 28, 2014 at 1:42 am

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

February 28, 2014 at 2:21 am

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

February 28, 2014 at 2:30 am

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

February 28, 2014 at 2:50 am

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

February 28, 2014 at 2:59 am

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}

February 28, 2014 at 4:54 am

Akash, what version of Powershell are you working with?