Categories

Delete all but the last N

I was asked a question about deleting files from a folder based on age.  The requirement was to delete all but the youngest N files.

One solution is a classic PowerShell one-liner. It is actually one PowerShell pipeline though I’ve split it across multiple lines for ease of reading.

Get-ChildItem -Path c:\temp -Filter *.tmp -File |
sort LastWriteTime -Descending |
select -Skip 5 |
Remove-Item

Use Get-Childitem to read the files you’re interested in. I’ve used the –File parameetr to restrict the examination to files.

Sort the files on LastWriteTime – you could use CreationTime if the files haven’t been changed since creation. You want the results sorted in descending order so the latest files are at the top of the list. Younger dates are greater than older dates.

use Select-Object to skip the first N (in this case 5) files and pipe everything else into remove-item.  Add a –whatif parameter to Remove-Item if want to see how its working before letting it loose.

A nice simple answer with a use for Select-Object’s –Skip parameter that I hadn’t thought of before.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>