Automatically retrieve a specific file via SFTP
How do I determine which file is the newest from a remote server that I am connected to via SFTP? My goal is to retrieve a specific file each day, via SFTP. The steps I will follow are:
Connect to server via SFTP
Retrieve the name of the file I need <-- need help with this step
Download it
I can figure out how to connect via SFTP from a script but I am not sure about the best way to go about determining which file to download.
For example, there are many files on the server named like so:
ABC-Alpha-Sun-May-12-abc123.xml.gz
ABC-Beta-Sun-May-12-abc123.xml.gz
I want to retrieve only that day's Alpha file. I assume that I would check the name for "May-12" to know if this is today's file? Or perhaps I should be checking the file creation date or modified date?
How would I actually retrieve the filename? Perhaps I retrieve the names of all of the files and then sort them somehow?
What would you recommend as the best way to achieve my goal?
Solution 1:
With WinSCP, it's easy. You can use the -latest
switch of the get
command in WinSCP scripting.
Also, in case your preferred scripting language is PowerShell, you can also consider using WinSCP .NET assembly with its Session.ListDirectory
method.
There are an example on WinSCP site, for all these approaches to downloading the most recent file.
(I'm the author of WinSCP)