Downloading file to timestamped-filename

Using WinSCP .NET Assembly

Use WinSCP .NET assembly from your favorite language. Use relevant construct of your language or API of your runtime environment for the file name formatting.

Advertisement

If you do not have your favorite language, use PowerShell:

param (
    $localPath = "c:\downloaded\",
    $remotePath = "/home/user/",
    $fileName = "download.txt"
)
         
try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
 
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "example.com"
        UserName = "user"
        Password = "mypassword"
        SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
    }
 
    $session = New-Object WinSCP.Session
 
    try
    {
        # Connect
        $session.Open($sessionOptions)
 
        # Format timestamp
        $stamp = $(Get-Date -Format "yyyyMMddHHmmss")
 
        # Download the file and throw on any error
        $session.GetFiles(
            ($remotePath + $fileName),
            ($localPath + $fileName + "." + $stamp)).Check()
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch
{
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
}

Advertisement

Using WinSCP Scripting

In scripting, you can use %TIMESTAMP% construct to insert a real-time to a script.

open mysession
get "/home/user/download.txt" "C:\downloaded\download.txt.%TIMESTAMP#yyyymmddhhnnss%"
exit

Further Reading

Last modified: by martin