Search code examples
batch-fileftpwinscp

Can I reference the batch file directory in a WinSCP batch script?


I am trying to upload a file to an FTP server using a batch command file. My code uses WinSCP and looks like this:

"C:\Program Files (x86)\WinSCP\WinSCP.com" ^
  /log="C:\Program Files (x86)\WinSCP\WinSCP.log" /ini=nul ^
  /command ^
    "open ftp://user:[email protected]/" ^
    "lcd %cd%" ^
    "cd /incoming/data" ^
    "put %~dp0file.txt" ^
    "exit"

set WINSCP_RESULT=%ERRORLEVEL%
if %WINSCP_RESULT% equ 0 (
  echo Success
) else (
  echo Error
)

exit /b %WINSCP_RESULT%

The log shows this:

> 2020-10-14 15:16:39.044 Script: put C:\Users\me\sharepoint - library folder\FTP\file.txt
. 2020-10-14 15:16:39.047 Copying 4 files/directories to remote directory "/incoming/data" - total size: 0
. 2020-10-14 15:16:39.047   PrTime: Yes; PrRO: No; Rght: rw-r--r--; PrR: No (No); FnCs: N; RIC: 0100; Resume: S (102400); CalcS: No; Mask: folder\FTP\file.txt
. 2020-10-14 15:16:39.047   TM: B; ClAr: No; RemEOF: No; RemBOM: No; CPS: 0; NewerOnly: No; EncryptNewFiles: Yes; ExcludeHiddenFiles: No; ExcludeEmptyDirectories: No; InclM: ; ResumeL: 0
. 2020-10-14 15:16:39.047   AscM: *.*html; *.htm; *.txt; *.php; *.php3; *.cgi; *.c; *.cpp; *.h; *.pas; *.bas; *.tex; *.pl; *.js; .htaccess; *.xtml; *.css; *.cfg; *.ini; *.sh; *.xml
* 2020-10-14 15:16:39.048 (EOSError) System Error.  Code: 2.

* 2020-10-14 15:16:39.048 The system cannot find the file specified

I'm expecting put %~dp0file.txt to give the full path to the file I want to upload and it looks like it gets it right from the log, but I don't know why it's trying to send 4 files or why it fails to find the specified file. I should note the path (folder/ftp) is actually much longer, the full path is 102 characters. The path contains spaces and one dash.


Solution

  • Your path contains spaces, so it has to be wrapped to double quotes:

        "put ""%~dp0file.txt""" ^
    

    The same goes for lcd. But as it makes no sense to use lcd, if you use an absolute path in the put command anyway, you can just remove the lcd altogether.