remove files older than days

Advertisement

Samer
Guest

remove files older than days

Hallo,

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:

Reply with quote

Advertisement

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

Re: remove files older than days

Combining these resources:
- https://winscp.net/eng/docs/library_example_listing_files_matching_wildcard
- https://winscp.net/eng/docs/script_download_most_recent_file
- https://stackoverflow.com/q/17829785/850848

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()
}

Reply with quote

Advertisement

You can post new topics in this forum