Deuian
Deuian

Reputation: 841

Using WinSCP in PowerShell to compare FTP to local directories

Trying to use WinSCP and PowerShell to list the remote and local directories comparing the lowest level to then transfer the directories on the remote missing from the local.

Listing works for both remote and local but the comparison -contains operator shows false even though when I Write-Host for $fileInfo it looks like they should match. I tried adding $fileInfo to an array for the comparison but it has much more than just the lowest directory like the attributes and other stuff for the directories.

$localpath = "C:\Users"
$remotePath = "/home"

Add-Type -Path "WinSCPnet.dll"

$localfolders = Get-ChildItem $localpath

$localtargets = @()
$remotetargets = @()

foreach ($f in $localfolders){
    $split = $f.FullName  -split '\\'
    $localtargets += $split[$split.Count-1]
}

$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Ftp
    HostName = "ftp.com"
    UserName = "user"
    Password = "password"
}

$session = New-Object WinSCP.Session

try
{
    $session.Open($sessionOptions)

    $fileInfos = $session.ListDirectory($remotePath)
    
    foreach ($fileInfo in $fileInfos.Files)
    {
        Write-Host $localtargets.Contains($fileInfo)                       
        $remotetargets += $fileInfo | Out-String   
    }
}

Upvotes: 2

Views: 671

Answers (2)

Martin Prikryl
Martin Prikryl

Reputation: 202168

The post by @JPBlack correctly answers your literal question.

Though note that WinSCP .NET assembly can synchronize your folder on its own using Session.SynchronizeDirectories:

$session.Open($sessionOptions)

$session.SynchronizeDirectories(
    [WinSCP.SynchronizationMode]::Local, $localpath, $remotePath, $False).Check()

Or if you just want to find the differences, use the Session.CompareDirectories.

Upvotes: 2

JPBlanc
JPBlanc

Reputation: 72610

As I understand $localtargets is just a list of strings representig file names, so you should just test if it contains the name of the file, in your last loop, can you test :

Write-Host $localtargets.Contains($fileInfo.Name)

Upvotes: 2

Related Questions