Uploading the most recent file

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.

Advertisements:
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 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)
 
        $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
        $session.PutFiles($session.EscapeFileMask($localPath + $latest.Name), $remotePath).Check()
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch [Exception]
{
    Write-Host ("Error: {0}" -f $_.Exception.Message)
    exit 1
}

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:

Further Reading

 
  script_upload_most_recent_file.txt · Last modified: by martin
 

Search Documentation

This page

Donate

About donations

$9   $19   $49   $99

About donations

Recommend

Associations

Site design by Black Gate