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

This topic contains 7 replies, has 3 voices, and was last updated by  Carlo Mancini 4 years, 3 months ago.

  • Author
  • #13379

    Akash Kumar

    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.

    Akash R.

  • #13380

    Carlo Mancini

    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


  • #13381

    Richard Siddaway

    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

  • #13382

    Carlo Mancini

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

  • #13383

    Richard Siddaway

    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

  • #13385

    Carlo Mancini

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

  • #13386

    Akash Kumar

    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}

  • #13388

    Carlo Mancini

    Akash, what version of Powershell are you working with?

You must be logged in to reply to this topic.