PowerShell for Windows Admins

Feb 26 2014   1:38PM GMT

Delete all but the last N

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: