Search code examples
batch-fileftpwinscp

WinSCP Script upload recursivelly all files matching a mask to the same folder


I have a text file that I am calling from a batch file and it is not putting files recursively in the FTP site. The folder structure has subfolders which contain the files I want to copy among many other files. The put files only copy C:\storage only. After reading the documentation and trying other method is still not copying files recursively. (no folders to be copied with the RDF from subfolders)

The folder structure is random on different PC:

  1. C:\storage\78286.S-92A.920024*.RDF
  2. C:\Storage\folder1\78286.S-92A.920024*.RDF
  3. C:\Storage\storage2\folder2\78286.S-92A.920024*.RDF

There are many RDF files, but the wildcard I am interested is the one you can see above. Basically I want to select all the *.RDF (as wildcard above from all the subfolders), but do not want the subfolders to be copied to the remote.

Please see code below.

option batch continue
option confirm off
option reconnecttime 900
open ftp://companyuser:[email protected]/    
lcd "C:\storage"
put "C:\storage\78286.S-92A.920024*.RDF"   "/"
put "C:\storage\*\78286.S-92A.920024*.RDF" "/"
close 
exit

Solution

  • It's not easy to do such custom processing with WinSCP scripting only.

    But with WinSCP .NET assembly from a PowerShell script, it's not difficult:

    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
    
    # Set up session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Ftp
        HostName = "ftp.example.com"
        UserName = "username"
        Password = "password"
    }
    
    $session = New-Object WinSCP.Session
    
    Write-Host "Connecting ..."
    $session.Open($sessionOptions)
    
    $localPath = "C:\storage"
    $remotePath = "/"
    $wildcard = "78286.S-92A.920024*.RDF"
    $localFiles = Get-ChildItem -Include $wildcard -Recurse -Path $localPath
    
    foreach ($localFile in $localFiles)
    {
        Write-Host "Uploading $($localFile.FullName)..."
        $session.PutFiles($localFile.FullName, $remotePath).Check()
    }
    

    Just extract a contents of WinSCP .NET assembly package along with the script (say flatupload.ps1) and run it like:

    powershell -ExecutionPolicy Bypass -File flatupload.ps1
    

    The code is partly based on WinSCP example Recursively move files in directory tree to/from SFTP/FTP server while preserving source directory structure.

    See also WinSCP forum question Ignore folder structure when copying the files.