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.


    # 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
        # Connect
        $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.EscapeFileMask($localPath + $latest.Name), $remotePath).Check()
        # Disconnect, clean up
    exit 0
    Write-Host "Error: $($_.Exception.Message)"
    exit 1

Using WinSCP Scripting

Use the -latest switch of the put command:

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


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

Further Reading

Last modified: by martin