This is an old revision of the document!

Deleting remote files after successful remote to local synchronization

For background, see article How do I create script that synchronizes files and deletes synchronized files from source afterward?

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

Advertisement

param (
    $localPath = "C:\backup\",
    $remotePath = "/home/user/data/"
)
 
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)
 
        # Synchronize files to local directory, collect results
        $synchronizationResult = $session.SynchronizeDirectories(
            [WinSCP.SynchronizationMode]::Local, $localPath, $remotePath, $False)
 
        # Deliberately not calling $synchronizationResult.Check
        # as that would abort our script on any error.
        # We will find any error in the loop below
        # (note that $synchronizationResult.Downloads is the only operation
        # collection of SynchronizationResult that can contain any items,
        # as we are not removing nor uploading anything)
 
        # Iterate over every download
        foreach ($download in $synchronizationResult.Downloads)
        {
            # Success or error?
            if ($download.Error -eq $Null)
            {
                Write-Host ("Download of {0} succeeded, removing from source" -f
                    $download.FileName)
                # Download succeeded, remove file from source
                $removalResult = $session.RemoveFiles($session.EscapeFileMask($download.FileName))
 
                if ($removalResult.IsSuccess)
                {
                    Write-Host ("Removing of file {0} succeeded" -f
                        $download.FileName)
                }
                else
                {
                    Write-Host ("Removing of file {0} failed" -f
                        $download.FileName)
                }
            }
            else
            {
                Write-Host ("Download of {0} failed: {1}" -f
                    $download.FileName, $download.Error.Message)
            }
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch [Exception]
{
    Write-Host $_.Exception.Message
    exit 1
}

Advertisement

Last modified: by martin