4

I have a script here that SFTP's files from one location to another, the script works fine however I'd like to change the script so that it only copies files that are not already present. Bit of a noob with powershell so any help would be greatly appreciated.

cd "c:\Program Files (x86)\WinSCP\" # location of .NET assembly ddl file

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 = "192.168.xxx.xxx"
    $sessionOptions.UserName = "xxxx"
    $sessionOptions.Password = "xxxx"
    $sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx"


    $session = New-Object WinSCP.Session

    try
    {
        # Connect
        $session.Open($sessionOptions)

        $stamp = Get-Date -f "yyyyMMdd"
        $fileName = "export_$stamp.txt"
        $remotePath = "/home/user/john/reports"
        $localPath = "\\fileserver\reports\"


        if ($session.FileExists($remotePath))
        {
            if (!(Test-Path $localPath))
            {
                Write-Host (
                    "File {0} exists, local backup {1} does not" -f
                    $remotePath, $localPath)
                $download = $True
            }


            if ($download)
            {
                # Download the file and throw on any error
                $session.GetFiles($remotePath, $localPath).Check()

                Write-Host "Download to backup done."
            }
        }
        else
        {
            Write-Host ("File {0} does not exist yet" -f $remotePath)
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }

    exit 0
}
catch [Exception]
{
    Write-Host $_.Exception.Message
    exit 1
}

Many Thanks.

3
  • Your code already does what you ask for. That's what the if (!(Test-Path $localPath)) branch is there for. Do you have some problem with that? Or do you want to change the script to allow transferring more files, not just one? Sep 3, 2014 at 13:10
  • The script above will overwrite all files in the destination directory Sep 3, 2014 at 15:00
  • OK, I didn't notice you tried to synchronize directories, not files. See my answer. Sep 3, 2014 at 19:20

1 Answer 1

1

The script your took from WinSCP example for the Session.GetFiles was designed for a single file only. You have tried to bend it to synchronize directories instead. That cannot work.

To synchronize directories, use the Session.SynchronizeDirectories:

# Synchronize files
$synchronizationResult = $session.SynchronizeDirectories(
    [WinSCP.SynchronizationMode]::Local, $localPath $remotePath)

# Throw on any error
$synchronizationResult.Check()

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .