How to delete all files in a directory except the three most recent?

Advertisement

semomaf
Joined:
Posts:
2

How to delete all files in a directory except the three most recent?

Hi guys.
I want a script to delete old files on the remote site but remain the last three files whatever age file is.
Is this possible?

Reply with quote

Advertisement

martin
Site Admin
martin avatar
Joined:
Posts:
41,548
Location:
Prague, Czechia

Re: How to delete all files in a directory except the three most recent?

Well, not with the simple scripting.
But with use of WinSCP .NET assembly from a PowerShell (or other) script, it's doable.
Something like this (but not tested):
$oldFiles =
    $session.ListDirectory($path) |
        Where-Object { -Not $_.IsDirectory } |
        Sort-Object -Property LastWriteTime -Descending |
        Select-Object -Skip 3
 
foreach ($oldFile in $oldFiles)
{
    $session.RemoveFile($transfer.FullName)
}

Reply with quote

Advertisement

You can post new topics in this forum