Search code examples
.netpowershellftpwinscpwinscp-net

Upload set of files using WinSCP.Session in PowerShell


I'm trying to upload three specific files, and get feedback for all three transfers. With the code below I only get

Upload of \xxxxxxxxxxxxxxxxxxx\Customerlocations.txt succeeded

I understand it's not adding transfers to the session but replacing it each time. I just don't know to adjust this so I get 3 transfers in $transferResult.Transfers.

Can someone point me in the correct direction?

# Set up session options
$sessionOptions = New-WinSCPSessionOption  -Protocol Ftp `
    -FtpSecure Implicit `
    -Credential xxxxxxxxxxxxxxxxxxx `
    -HostName "xxxxxxxxxxxxxxxxxxx " `
    -TlsHostCertificateFingerprint "xxxxxxxxxxxxxxxxxxx "

$session = New-Object WinSCP.Session 
$session.ExecutablePath = "C:\xxxxxxxxxxxxxxxxxxx\WinSCP.exe"
try
{
    # Connect
    $session.Open($sessionOptions)

    # Download files
    $transferOptions = New-Object WinSCP.TransferOptions
    $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

    $transferResult =  
        $session.PutFiles("\\xxxxxxxxxxxxxxxxxxx\Orders.txt", "/Orders.txt", $False, $transferOptions)
    $transferResult = 
        $session.PutFiles("\\xxxxxxxxxxxxxxxxxxx\Assortment.txt", "/Assortment.txt", $False, $transferOptions)
    $transferResult = 
        $session.PutFiles("\\xxxxxxxxxxxxxxxxxxx\Customerlocations.txt", "/Customerlocations.txt", $False, $transferOptions)

    # Throw on any error
    $transferResult.Check()

    # Print results
    foreach ($transfer in $transferResult.Transfers)
    {
        Write-Host "Upload of $($transfer.FileName) succeeded"
    }

    # Disconnect, clean up
    $session.Dispose()
}
finally
{
    $session.Dispose()
}

Solution

  • You have to inspect results of each Session.PutFiles call separately. To avoid repeating the code, you can use a loop like this:

    $paths = @("...\Orders.txt", "...\Assortment.txt", "...\Customerlocations.txt")
    foreach ($path in $paths)
    {
        $transferResult = $session.PutFiles($path, "/", $False, $transferOptions)
        # Throw on any error
        $transferResult.Check()
     
        # Print results
        foreach ($transfer in $transferResult.Transfers)
        {
            Write-Host "Upload of $($transfer.FileName) succeeded"
        }
    }