Differences
This shows you the differences between the selected revisions of the page.
| script_download_most_recent_file 2015-08-25 | script_download_most_recent_file 2022-06-16 (current) | ||
| Line 2: | Line 2: | ||
| ===== [[library]] Using WinSCP .NET Assembly ===== | ===== [[library]] Using WinSCP .NET Assembly ===== | ||
| + | |||
| + | ==== [[powershell]] PowerShell ==== | ||
| The following example uses [[library|WinSCP .NET assembly]] from a [[library_powershell|PowerShell]] script. If you have another preferred language, you can easily translate it. | The following example uses [[library|WinSCP .NET assembly]] from a [[library_powershell|PowerShell]] script. If you have another preferred language, you can easily translate it. | ||
| <code powershell> | <code powershell> | ||
| param ( | param ( | ||
| - | $session = "sftp://user:mypassword;fingerprint=ssh-rsa-xx-xx-xx@example.com/", | + | $localPath = "c:\downloaded", |
| - | $remotePath = "/path", | + | $remotePath = "/home/user" |
| - | $outFile = "listing.csv" | + | |
| ) | ) | ||
| Line 17: | Line 18: | ||
| # Setup session options | # Setup session options | ||
| - | $sessionOptions = New-Object WinSCP.SessionOptions | + | $sessionOptions = New-Object WinSCP.SessionOptions -Property @{ |
| - | ···$sessionOptions.ParseUrl($session) | + | ·······Protocol = [WinSCP.Protocol]::Sftp |
| + | HostName = "example.com" | ||
| + | UserName = "user" | ||
| + | Password = "mypassword" | ||
| + | SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..." | ||
| + | } | ||
| + | |||
| + | ····$session = New-Object WinSCP.Session | ||
| try | try | ||
| { | { | ||
| # Connect | # Connect | ||
| - | Write-Host "Connecting..." | ||
| - | $session = New-Object WinSCP.Session | ||
| $session.Open($sessionOptions) | $session.Open($sessionOptions) | ||
| + | |||
| + | # Get list of files in the directory | ||
| + | $directoryInfo = $session.ListDirectory($remotePath) | ||
| - | # Retrieve listing | + | # Select the most recent file |
| - | Write-Host "Listing..." | + | $latest = |
| - | ·······$directory = $session.ListDirectory($remotePath) | + | ···········$directoryInfo.Files | |
| + | ············Where-Object { -Not $_.IsDirectory } | | ||
| + | ············Sort-Object LastWriteTime -Descending | | ||
| + | ············Select-Object -First 1 | ||
| - | # Remove output file if it exists | + | # Any file at all? |
| - | if (Test-Path $outFile) | + | if ($latest -eq $Null) |
| { | { | ||
| - | Remove-Item $outFile | + | Write-Host "No file found" |
| - | ········} | + | ···········exit 1 |
| - | + | ||
| - | # Generate a custom listing for ach file in the output file | + | |
| - | # Using UTF-16 (Unicode) encoding that Microsoft Excel likes. | + | |
| - | foreach ($fileInfo in $directory.Files) | + | |
| - | { | + | |
| - | ("`"{0}`"`t{1}`t`"{2}`"" -f $fileInfo.Name, $fileInfo.Length, $fileInfo.LastWriteTime) | Out-File -Append $outFile -Encoding Unicode | + | |
| } | } | ||
| - | Write-Host "Done" | + | # Download the selected file |
| + | ·······$session.GetFileToDirectory($latest.FullName, $localPath) | Out-Null | ||
| } | } | ||
| finally | finally | ||
| Line 54: | Line 61: | ||
| exit 0 | exit 0 | ||
| } | } | ||
| - | catch [Exception] | + | catch |
| { | { | ||
| - | Write-Host $_.Exception.Message | + | Write-Host "Error: $($_.Exception.Message)" |
| exit 1 | exit 1 | ||
| } | } | ||
| </code> | </code> | ||
| - | ===== [[scripting]] Using WinSCP Scripting ===== | + | ==== [[csharp]] C# ==== |
| - | You may have WinSCP produce [[logging_xml|XML log]] with the listing and convert it to your custom format [[logging_xml#xslt|using XSLT]]: | + | |
| - | Use the following Windows batch file (''listing.bat''): | + | <code csharp> |
| + | using System; | ||
| + | using System.Linq; | ||
| + | using WinSCP; | ||
| - | <code batch> | + | class Program |
| - | @echo off | + | { |
| - | set XMLLOG=script.xml | + | ···static int Main(string[] args) |
| - | winscp.com /log=script.log /xmllog=%XMLLOG% /command ^ | + | ····{ |
| - | ···"open mysession" ^ | + | try |
| - | ···"ls /path" ^ | + | ········{ |
| - | ···"exit" | + | ···········// Setup session options |
| - | if %ERRORLEVEL% == 0 msxsl.exe %XMLLOG% listing.xsl > listing_script.csv | + | SessionOptions sessionOptions = new SessionOptions |
| + | { | ||
| + | Protocol = Protocol.Sftp, | ||
| + | ················HostName = "example.com", | ||
| + | ···············UserName = "user", | ||
| + | ···············Password = "mypassword", | ||
| + | ···············SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...", | ||
| + | }; | ||
| + | |||
| + | ···········using (Session session = new Session()) | ||
| + | { | ||
| + | // Connect | ||
| + | session.Open(sessionOptions); | ||
| + | |||
| + | const string remotePath = "/home/user"; | ||
| + | const string localPath = @"C:\downloaded"; | ||
| + | |||
| + | ···············// Get list of files in the directory | ||
| + | RemoteDirectoryInfo directoryInfo = session.ListDirectory(remotePath); | ||
| + | |||
| + | // Select the most recent file | ||
| + | RemoteFileInfo latest = | ||
| + | directoryInfo.Files | ||
| + | ·······················.Where(file => !file.IsDirectory) | ||
| + | .OrderByDescending(file => file.LastWriteTime) | ||
| + | .FirstOrDefault(); | ||
| + | |||
| + | // Any file at all? | ||
| + | if (latest == null) | ||
| + | { | ||
| + | throw new Exception("No file found"); | ||
| + | } | ||
| + | |||
| + | // Download the selected file | ||
| + | session.GetFileToDirectory(latest.FullName, localPath); | ||
| + | } | ||
| + | |||
| + | return 0; | ||
| + | } | ||
| + | catch (Exception e) | ||
| + | { | ||
| + | Console.WriteLine("Error: {0}", e); | ||
| + | return 1; | ||
| + | } | ||
| + | } | ||
| + | } | ||
| </code> | </code> | ||
| - | Where the ''listing.xsl'' may look like: | + | ==== [[vbnet]] VB.NET ==== |
| - | <code xml> | + | The following snippet selects the most recent file from a directory listing. Most of the remaining code should be trivial to translate from the above C# example. |
| - | <?xml version="1.0" encoding="UTF-8"?> | + | |
| - | <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:winscp="http://winscp.net/schema/session/1.0"> | + | <code vbnet> |
| - | <!-- Using UTF-16 encoding that Microsoft Excel likes --> | + | Dim latest As RemoteFileInfo = |
| - | <xsl:output method="text" encoding="UTF-16"/> | + | ···directoryInfo.Files _ |
| - | <xsl:strip-space elements="*"/> | + | ·······.Where(Function(file) Not file.IsDirectory) _ |
| - | ···<xsl:template match='winscp:ls[winscp:result[@success="true"]]/winscp:files/winscp:file'> | + | ·······.OrderByDescending(Function(file) file.LastWriteTime) _ |
| - | ·········<xsl:text>&quot;</xsl:text> | + | ·······.FirstOrDefault() |
| - | <xsl:value-of select="winscp:filename/@value"/> | + | |
| - | ········<xsl:text>"	</xsl:text> | + | |
| - | ········<xsl:value-of select="winscp:size/@value"/> | + | |
| - | <xsl:text>	"</xsl:text> | + | |
| - | ········<xsl:value-of select="winscp:modification/@value"/> | + | |
| - | <xsl:text>"
</xsl:text> | + | |
| - | ···</xsl:template> | + | |
| - | </xsl:stylesheet> | + | |
| </code> | </code> | ||
| + | |||
| + | ===== [[scripting]] Using WinSCP Scripting ===== | ||
| + | Use the ''[[scriptcommand_get#latest|-latest]]'' switch of the ''[[scriptcommand_get|get]]'' command: | ||
| + | |||
| + | <code winscp> | ||
| + | get -latest /home/user/* c:\downloaded\ | ||
| + | </code> | ||
| + | |||
| + | ===== [[alternatives]] Alternatives ===== | ||
| + | |||
| + | Some of following alternatives can be easier to implement or actually even more appropriate for your specific task: | ||
| + | |||
| + | * Synchronizing a remote directory to a local directory (using ''[[scriptcommand_synchronize|synchronize local]]'' in scripting; or ''[[library_session_synchronizedirectories|Session.SynchronizeDirectories]]'' with ''mode'' parameter set to ''SynchronizationMode.Local'' in .NET assembly); | ||
| + | * Downloading all files created in the last 24 hours (using [[file_mask|file mask]] ''*>=1D''; e.g. ''%%get -filemask="*>=1D" /home/user/*%%'', or an equivalent in .NET assembly). | ||
| + | * Downloading all files created today (using the [[file_mask#today|''today'' keyword in the file mask]]; e.g. ''%%get -filemask="*>=today" /home/user/*%%'', or an equivalent in .NET assembly). | ||
| + | * If you need to download all files that were not downloaded yet, but you do not keep local copies of the files to synchronize the remote directory against, see [[library_example_remember_downloaded_files|*]]. | ||
| ===== Further Reading ===== | ===== Further Reading ===== | ||
| Line 100: | Line 162: | ||
| * Guide to [[guide_automation|scripting/automation]]; | * Guide to [[guide_automation|scripting/automation]]; | ||
| * [[library|WinSCP .NET assembly]]; | * [[library|WinSCP .NET assembly]]; | ||
| - | * [[library_powershell|Using WinSCP .NET Assembly from PowerShell]]; | + | * [[library_powershell|*]]. |
| - | ··* [[logging_xml|XML logging]]. | + | |