Topic "Powershell Script to SFTP New files"

Author Message
[View user's profile]

Joined: 2014-09-03
Posts: 1
Location: UK
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 newb with powershell so any help would be greatly appreciated.

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

# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = ""
$sessionOptions.UserName = "xxxx"
$sessionOptions.Password = "xxxx"
$sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx"

$session = New-Object WinSCP.Session

# Connect

$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."
Write-Host ("File {0} does not exist yet" -f $remotePath)
# Disconnect, clean up

exit 0
catch [Exception]
Write-Host $_.Exception.Message
exit 1
[View user's profile]
Site Admin
Joined: 2002-12-10
Posts: 26890
Location: Prague, Czechia
See my answer to your duplicate question on

The script your took from WinSCP example for 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 Session.SynchronizeDirectories:

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

# Throw on any error

You can post new topics in this forum


What is WinSCP?

It is award-winning SFTP client, SCP client, FTPS client and FTP client integrated into one software program for file transfer to FTP server or secure SFTP server. [More]

And it's free!


About donations

$9   $19   $49   $99

About donations


WinSCP Privacy Policy

WinSCP License