Search code examples
batch-filesftpwinscp

Some WinSCP commands in a batch file are not working


I am trying to download files from an SFTP server to my local machine, with created a date-wise folder using WinSCP. But it's falling at the point of lcd.

Here is my script.

@echo off

set datetime=%date:~7,2%%date:~4,2%%date:~10,4%
set "mydir=D:\Test\%datetime%\"
mkdir "%mydir%"

echo My Directory is created "%mydir%"

"C:\Program Files (x86)\WinSCP\WinSCP.com" ^
/log="D:\temp\WinSCP.log" /ini=nul ^
/command ^
"open sftp://username:password@sftp.server1/logs/Test/ -hostkey=""ssh-key=""" ^

"lcd %mydir%" ^

"get *.xml>1D" ^
"exit"

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

exit /b %WINSCP_RESULT%```

Here is the error in the log:

> 2021-03-18 09:17:10.392 lcd D:\Test\18032021\
< 2021-03-18 09:17:10.392 Script: Unknown command '
< 2021-03-18 09:17:10.392 lcd'.
. 2021-03-18 09:17:10.393 Script: Failed
. 2021-03-18 09:17:10.393 Script: Exit code: 1
. 2021-03-18 09:17:10.393 Closing connection.
. 2021-03-18 09:17:10.393 Sending special code: 1
. 2021-03-18 09:17:10.579 Session sent command exit status 0
. 2021-03-18 09:17:10.579 Main session channel closed
. 2021-03-18 09:17:10.580 All channels closed

I tried with many options but it's still failing. Any suggestion pointer much appreciated.

Regards, Aniruddha


Solution

  • The batch file in your question cannot produce the error you are describing. It won't even pass the lcd to WinSCP, as your batch file syntax is wrong.

    When you want to break a command in a batch file to multiple lines, you need to end each broken line with ^ and the next line needs to be indented.

    • Your empty lines do not end with ^ (like the one between open and lcd command)
    • None of your continuation lines are indented.

    This should work:

    "C:\Program Files (x86)\WinSCP\WinSCP.com" ^
      /log="D:\temp\WinSCP.log" /ini=nul ^
      /command ^
        "open sftp://username:password@sftp.server1/logs/Test/ -hostkey=""ssh-key=""" ^
        "lcd %mydir%" ^
        "get *.xml>1D" ^
        "exit"
    

    See WinSCP FAQ Why are some WinSCP scripting commands specified in a batch file not executed/failing?