This is an old revision of the document!

Useful Scripts

Advertisement

Moving local files to different location after successful upload

Using WinSCP .NET Assembly

Use WinSCP .NET assembly from your favourite language.

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

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)
 
        $localPath = "C:\upload\*"
        $remotePath = "/home/user/"
        $backupPath = "C:\backup\"
 
        # Upload files, collect results
        $transferResult = $session.PutFiles($localPath, $remotePath)
 
        # Iterate over every transfer
        foreach ($transfer in $transferResult.Transfers)
        {
            # Success or error?
            if ($transfer.Error -eq $Null)
            {
                Write-Host ("Upload of {0} succeeded, moving to backup" -f
                    $transfer.FileName)
                # Upload succeeded, move source file to backup
                Move-Item $transfer.FileName $backupPath
            }
            else
            {
                Write-Host ("Upload of {0} failed: {1}" -f
                    $transfer.FileName, $transfer.Error.Message)
            }
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch [Exception]
{
    Write-Host $_.Exception.Message
    exit 1
}

Advertisement

Using WinSCP Scripting

WinSCP scripting does not support move command for local files. Instead you can combine WinSCP script with batch file:

option batch abort
option confirm off
# Connect
open mysession
# Upload the files
put *.*

Launch the above script from batch file like the one below:

winscp.com /script=example.txt
if ERRORLEVEL 1 goto error

echo Upload succeeded, moving local files
move *.* c:\backup\
exit

:error
echo Upload failed, keeping local files

Other Examples

Other Examples

Advertisement

Last modified: by 122.181.146.2