Quantcast
Channel: PowerShell.org » All Posts
Viewing all articles
Browse latest Browse all 13067

Reply To: Remove folders in a directory but keep the three latest (creation date)

$
0
0

This is one of those problems that is quite handily solved with a single pipeline, thanks to PowerShell's handy generic -Object commands for filtering / sorting / selecting:

Get-ChildItem D:\Websites -Directory |
Sort-Object CreationTime -Descending |
Select-Object -Skip 3 |
Remove-Item -Recurse -Force -WhatIf

If you're running PowerShell 2.0 and don't have the -Directory switch on Get-ChildItem, no problem: stick a Where-Object in the pipeline:

Get-ChildItem D:\Websites |
Where-Object { $_.PSIsContainer } |
Sort-Object CreationTime -Descending |
Select-Object -Skip 3 |
Remove-Item -Recurse -Force -WhatIf

(Remove the -WhatIf switch from Remove-Item to make this actually delete things.)

There are times when people go overboard with the "one-liner" approach, but for this purpose, it's great. It's a lot like writing a SQL or LINQ query.


Viewing all articles
Browse latest Browse all 13067

Trending Articles