Search code examples
powershellftpwinscpwinscp-net

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   
    }
}

Solution

  • 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)