Moving local files to different location after successful upload

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.


param (
    $localPath = "C:\upload\*",
    $remotePath = "/home/user/",
    $backupPath = "C:\backup\"
    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = ""
        UserName = "user"
        Password = "mypassword"
        SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
    $session = New-Object WinSCP.Session
        # Connect
        # 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 $($transfer.FileName) succeeded, moving to backup"
                # Upload succeeded, move source file to backup
                Move-Item $transfer.FileName $backupPath
                Write-Host "Upload of $($transfer.FileName) failed: $($transfer.Error.Message)"
        # Disconnect, clean up
    exit 0
    Write-Host "Error: $($_.Exception.Message)"
    exit 1


Using WinSCP Scripting

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

# Connect
open mysession
# Upload the files
put *.*
# Exit WinSCP

Launch the above script from batch file like the one below: /script=example.txt
if %ERRORLEVEL% neq 0 goto error
echo Upload succeeded, moving local files
move *.* c:\backup\
exit /b 0
echo Upload failed, keeping local files
exit /b 1

Contrary to the PowerShell script above, this solution is not transactionally safe. If new files appear in the local folder between times the upload starts and the archiving/moving starts, the new files will not get uploaded. For this reason, prefer using the PowerShell script.

Another option is to move the files to an intermediate/temporary folder first, upload from there, and then move them to the backup location.

Further Reading

Last modified: by martin