Uploading a list of files

Using WinSCP .NET Assembly

The following example uses WinSCP .NET assembly from a PowerShell script. If you have another preferred language, you can easily translate it.

Advertisement

try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
 
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "example.com"
        UserName = "user"
        Password = "mypassword"
        SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
    }
 
    $session = New-Object WinSCP.Session
 
    try
    {
        # Connect
        $session.Open($sessionOptions)
 
        $remotePath = "/home/user/"
 
        $lines = Get-Content "list.txt"
 
        foreach ($line in $lines)
        {
            Write-Host "Uploading $line ..."
            $session.PutFiles($line, $remotePath).Check()
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch
{
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
}

Advertisement

Using WinSCP Scripting

You may use following batch file that calls generated WinSCP script:

@echo off
set SESSION=sftp://user:password;fingerprint=ssh-rsa-xxxxxxxxxxx...@example.com/
set REMOTE_PATH=/home/user/
 
(
  echo open %SESSION%
  echo cd %REMOTE_PATH%
 
  rem Generate "put" command for each line in list file
  for /F %%i in (list.txt) do echo put "%%i"
 
  echo exit
) > script.tmp
 
winscp.com /ini=nul /log=script.log /script=script.tmp
set RESULT=%ERRORLEVEL%
 
del script.tmp
 
rem Propagating WinSCP exit code
exit /b %RESULT%

Further Reading

Last modified: by martin