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
martin

Re: Archiving on the remote site during download

Your placement is correct (after all, it's the same what the original code does).
But it's Session.MoveFile, not Session.MoveFiles. And you need to use $transfer.FileName. And Session.MoveFile does not return anything.

$session.MoveFiles($transfer.FileName, $backupPath)


See also
https://stackoverflow.com/q/28436903/850848
https://stackoverflow.com/q/48311614/850848
Vann_the_Red

Archiving on the remote site during download

Good afternoon, all! I was adapting the script provided at: https://winscp.net/eng/docs/script_local_move_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
}