This is an old revision of the document!

Downloading file to timestamped-filename

Advertisement

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.

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
    $sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
    $sessionOptions.HostName = "example.com"
    $sessionOptions.UserName = "user"
    $sessionOptions.Password = "mypassword"
    $sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
 
    $session = New-Object WinSCP.Session
 
    try
    {
        # Connect
        $session.Open($sessionOptions)
 
        # Format timestamp
        $stamp = $(Get-Date -f "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 [Exception]
{
    Write-Host $_.Exception.Message
    exit 1
}

Advertisement

Using WinSCP Scripting

Using TIMESTAMP Variable

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

option batch abort
option confirm off
open mysession
get "/home/user/download.txt" "C:\downloaded\download.txt.%TIMESTAMP#yyyymmddhhnnss%"
exit

From a Batch File

In Windows batch file, you may retrieve current time in locale-independent format using command wmic os get LocalDateTime. You can parse the value using using string processing syntax:

@echo off
 
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set LDT=%%j
set STAMP=%LDT:~0,4%%LDT:~4,2%%LDT:~6,2%%LDT:~8,2%%LDT:~10,2%%LDT:~12,2%
 
winscp.com /script=script.txt

Note that the expression after set STAMP= shows how to extract individual date/time components, in case you need to interleave them by some punctuation. If not, you can replace it by simple %LDT:~0,14%.

The script.txt should make use of the variable STAMP using %STAMP% syntax. For example:

option batch abort
option confirm off
open mysession
get "/home/user/download.txt" "C:\downloaded\download.txt.%STAMP%"
exit

From a JScript

You may use following Windows script host JScript code (example.js):

// Local path to download to (keep trailing slash)
var LOCALPATH = "c:\\downloaded\\";
// Remote path to download from (keep trailing slash)
var REMOTEPATH = "/home/user/";
// File to download
var FILE = "download.txt";
// Session to connect to
var SESSION = "session";
// Path to winscp.com
var WINSCP = "c:\\program files\\winscp\\winscp.com";
 
// helper function to pad zeroes to the left of number
function pad(n, len)
{
    var s = n.toString();
    while (s.length < len)
    {
        s = '0' + s;
    }
    return s;
}
 
var date = new Date();
 
// format timestamp
var stamp = 
    pad(date.getFullYear(), 4) +
    pad(date.getMonth(), 2) +
    pad(date.getDate(), 2) +
    pad(date.getHours(), 2) +
    pad(date.getMinutes(), 2) +
    pad(date.getSeconds(), 2);
 
var shell = WScript.CreateObject("WScript.Shell");
 
// run winscp to download the file into timestamped-filename
exec = shell.Exec("\"" + WINSCP + "\"");
exec.StdIn.Write(
    "option batch abort\n" +
    "open \"" + SESSION + "\"\n" +
    "get \"" + REMOTEPATH + FILE + "\" \"" + LOCALPATH + FILE + "." + stamp + "\"\n" +
    "exit\n");
 
// wait until it finishes and collect its output
var output = exec.StdOut.ReadAll();
// optionally print the output
WScript.Echo(output);

Advertisement

Run the script with command:

cscript /nologo example.js

Further Reading

Last modified: by martin