Remove first 5 items in every subfolder in directory

Viewed 80

I have a large frame sequence split into 245 frames per clip, the first 5 of each need to be deleted. I already have a powershell script that sorts all of these into folders of 245. All I need to do is, in each folder, delete the first five frames. Alternatively I could delete 5, skip 240, delete 5, etc. before sorting them into folders but I could not figure that out either. What script could I use to do this?

1 Answers

Get the folders to iterate through with Get-ChildItem, Sort them if needed (default sort is by file name ascending), choose the items to delete with Select, and remove with Remove-Item:

Foreach ($subfolder in (Get-ChildItem 'c:\path\to\clips\' -Directory)) {
  Get-ChildItem $subfolder -File | 
    # Sort -Property Name -Descending | ## Optionally sort by name/date/whatever needed.
    Select -First 5 |
    Remove-Item -WhatIf
}

I recommend running with -WhatIf to validate you're getting the right files before deleting them.

Related