Uploading the most recent file

Advertisement

Using WinSCP .NET Assembly

The following example uses WinSCP .NET assembly from a PowerShell script. If you have another preferred language, you can easily translate it.

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 xxxxxx..."
    }
 
    $session = New-Object WinSCP.Session
 
    try
    {
        # Connect
        $session.Open($sessionOptions)
 
        $localPath = "c:\toupload"
        $remotePath = "/home/user"
 
        # Select the most recent file.
        # The !$_.PsIsContainer test excludes subdirectories.
        # With PowerShell 3.0, you can replace this with -File switch of Get-ChildItem. 
        $latest =
            Get-ChildItem -Path $localPath |
            Where-Object {!$_.PsIsContainer} |
            Sort-Object LastWriteTime -Descending |
            Select-Object -First 1
 
        # Any file at all?
        if ($latest -eq $Null)
        {
            Write-Host "No file found"
            exit 1
        }
 
        # Upload the selected file
        $sourcePath = Join-Path $localPath $latest.Name
        $session.PutFiles(
            [WinSCP.RemotePath]::EscapeFileMask($sourcePath),
            [WinSCP.RemotePath]::CombinePaths($remotePath, "*")).Check()
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch
{
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
}

Advertisement

Using WinSCP Scripting

Use the -latest switch of the put command:

put -latest c:\toupload\* /home/user/

Alternatives

Some of following alternatives can be easier to implement or actually even more appropriate for your specific task:

  • Synchronizing a local directory to a remote directory (using synchronize remote in scripting or Session.SynchronizeDirectories with mode parameter set to SynchronizationMode.Remote in .NET assembly);
  • Uploading all files created in the last 24 hours (using file mask *>=1D; e.g. put -filemask="*>=1D" c:\toupload\*, or an equivalent in .NET assembly).
  • Uploading all files created today (using %TIMESTAMP% syntax to format file mask with today’s time constraint, e.g. put -filemask="*>=%TIMESTAMP#yyyy-mm-dd%" c:\toupload\*, or an equivalent in .NET assembly).

Further Reading

Last modified: by martin