Search code examples
batch-filecmdftpwinscp

How to download newer files using WinSCP and save them to two local folders?


I have file in a folder (ftp_region) whose contents is similar to data in my FTP.

How to download newer files from my FTP and save them to two local folders (ftp_region and other folder)

For now, I use this:

open "my ftp address"
get -neweronly "..." "..."

Solution

  • You cannot do this with a plain WinSCP scripting.

    You better use the WinSCP .NET assembly. It allows you to process the downloaded files.

    An example code in PowerShell:

    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
    
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Ftp
        HostName = "ftp.example.com"
        UserName = "user"
        Password = "password"
    }
    
    Write-Host "Connecting..."
    $session = New-Object WinSCP.Session
    # $session.SessionLogPath = "C:\path\to\log\sync.log"
    $session.Open($sessionOptions)
    
    $remotePath = "/remote/path"
    $localPathPrimary = "C:\backup\primary"
    $localPathSecondary = "C:\backup\secondary"
    
    Write-Host "Synchronizing..."
    $result =
        $session.SynchronizeDirectories(
            [WinSCP.SynchronizationMode]::Local, $localPathPrimary, $remotePath,
            $False)
    $result.Check()
    
    Write-Host "Copying downloaded files to secondary backup..."
    foreach ($download in $result.Downloads)
    {
        $filename = (Split-Path -Leaf $download.Destination)
        $localFilePathSecondary = (Join-Path $localPathSecondary $filename)
        Copy-Item $download.Destination $localFilePathSecondary
        Write-Host "File $filename archived to both folders."
    }
    

    The code is based on an official example Deleting remote files after successful remote to local synchronization.