Topic "remove files older than days"

Author Message



I would really be gratefull if you can help me with the below question:

I have made a script using powershell to zip files and upload it to an SFTP server and then deleting the local zip file, everything is working great.

My question is, after uploading the file I want to check all the files in the remote directory (which holds the zip files) and delete the ones which are older than 15 day.

I think I should use the $session.RemoveFiles(" ")

But how im going to difine the "15 days", it can be done by WinSCP commands but I want it by Powershell so the whole script will be in one language.

Thank you very much for your advice! Idea
[View user's profile]
Site Admin
Joined: 2002-12-10
Posts: 24759
Location: Prague, Czechia
Combining these resources:

You get a code like:

$directoryInfo = $session.ListDirectory($remotePath)

$limit = (Get-Date).AddDays(-15)

$oldFiles =
    $directoryInfo.Files |
    Where-Object { $_.LastWriteTime -lt $limit }

foreach ($oldFileInfo in $oldFiles)
    $session.RemoveFiles($session.EscapeFileMask($remotePath + "/" + $oldFileInfo.Name)).Check()


Thank you prikryl for the code. I will definitely use it.

You can post new topics in this forum

Search Site

What is WinSCP?

It is award-winning SFTP client, SCP client, FTPS client and FTP client integrated into one software program for file transfer to FTP server or secure SFTP server. [More]

And it's free!


About donations

$9   $19   $49   $99

About donations


WinSCP Privacy Policy

WinSCP License