Powershell script to delete oldest files (not relative to current date)

Solution 1:

Usage: yourScript.ps1 -Path path\to\run\against [-NumberToSave N]


$items = Get-ChildItem "$Path\*.ext" |
    Where-Object Name -match "\d\d\d\d\d\d\d\d-\d\d\d\d\.ext" |
    Sort-Object Name -Descending

if ($NumberToSave -lt $items.Count)
    $items[$NumberToSave..($items.Count-1)] | Remove-Item

I don't expect this is really any better than @John's, I just made this to try parameters, regexp, and not using a loop. Doing a regex match does have the possible benefit of ruling out other files with .ext that don't match the format (e.g. 20130504-1200.txt.ext, 20.ext), but it's doubtful that applies.

I was bummed to find out that if $NumberToSave = $items.Count then the if statement is needed, otherwise it wouldn't be there. Technically:

$items[$numberToSave..$items.Count] | Remove-Item 

works fine (PowerShell doesn't seem to error if you reference past the array bounds, it just handles and ignores it?) but that seemed potentially confusing.

Solution 2:

$n = x

$items = Get-ChildItem path_to_folder\*.ext

$items | 
  Sort-Object Name -Descending | 
  Select-Object -Last ($items.count - $n) | 
  Foreach-Object { Remove-Item $_ }