Post a reply

Options
Add an Attachment

If you do not want to add an Attachment to your Post, please leave the Fields blank.

(maximum 10 MB; please compress large files; only common media, archive, text and programming file formats are allowed)

Options

Topic review

Vann_the_Red

Thank you, Martin. Very helpful as always.

Regards,
VtR
Vann_the_Red

Archiving on the remote site during download

Good afternoon, all! I was adapting the script provided at: Moving local files to different location after successful upload
to download from a remote site and then archive to a different directory on that remote site. I'm uncertain, though, where the Session.MoveFiles call should live. Any advice would be greatly appreciated. Code below.

Regards,
VtR

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