Downloading all files from FTP/SFTP to the same local folder

When downloading a remote directory tree, WinSCP recreates an equivalent tree locally.

If you want to download all files (or all files matching a certain criteria) from the remote directory tree to the same local folder, it is more complicated.

Advertisement

Using WinSCP .NET Assembly

The following PowerShell script snippet enumerates all remote files matching a filemask, and downloads them one-by-one to the same local folder:

$remotePath = "/remote/path"
$localPath = "C:\local\path"
$mask = "*.txt"
 
$files = $session.EnumerateRemoteFiles(
             $remotePath, $mask, [WinSCP.EnumerationOptions]::AllDirectories)
 
foreach ($fileInfo in $files)
{
    Write-Host "Downloading $($fileInfo.FullName) ..."
    $filePath = [WinSCP.RemotePath]::EscapeFileMask($fileInfo.FullName)
    $session.GetFiles($filePath, $localPath + "\*").Check() 
}

Using WinSCP scripting

It is too complicated to implement this task with a simple scripting. If you do not want to use the .NET assembly, you can at least download the remote directory tree as is, and then flatten it locally:

@echo off
set TMPPATH=%temp%\csvtmp
mkdir "%TMPPATH%"
winscp.com /command ^
    "open sftp://user:password@example.com/" ^
    "get ""/remote/path/*"" -filemask=*.txt ""%TMPPATH%""" ^
    "exit"
for /r "%TMPPATH%" %%f in ("*.*") do move "%%f" "C:\local\path\"
rd /s /q "%TMPPATH%"

Advertisement

Further reading

Last modified: by martin