Search code examples
batch-filesftpfile-transferwinscp

Error in Automation of uploading SFTP file of WinSCP using batch script


I am very new to both WinSCP and batch file scripting. So excuse me if this question is very basic. I am trying to upload file from my local folder to remote folder using batch file. The name of the file changes every week. I am facing 2 problems.

  1. I am using below code in batch file to upload a file to WinSCP
"C:\Program Files (x86)\WinSCP\WinSCP.com" ^
  /command ^
    open sftp://descartes:z*******s@sftp.psdataservices.com/ -hostkey="ssh-rsa 1024 ******=" ^
    "lcd  C:\Users\kajal.jain\Downloads\New folder" ^
    "cd /" ^
    "put Week 7 2022 Portal Data" ^
    "exit"

I am getting below error.

Unknown command 'lcd  C:\Users\kajal.jain\Downloads\New folder'.
Same for cd 
  1. As the name of file to be uploaded changes every week. How can I automate it in the Put command?

Solution

    1. Add quotes! Since WinSCP needs all its commands with spaces surrounded by double-quotes (see syntax reference here), I'd first put some around that open ... command, and then around other paths in your lcd and put commands. You can use two double-quotes to mean a literal " in your command.

    2. Pass in a filename. You can use %1 to refer to the first command-line argument to this batch file. So if you save the script below as "upload.bat"...

    "C:\Program Files (x86)\WinSCP\WinSCP.com" ^
      /command ^
        "open sftp://descartes:z*******s@sftp.psdataservices.com/ -hostkey=""ssh-rsa 1024 ******=""" ^
        "lcd  ""C:\Users\kajal.jain\Downloads\New folder""" ^
        "cd /" ^
        "put %1" ^
        "exit"
    

    ...then from the command line you could type

    upload "Week 7 2022 Portal Data"
    

    to have it upload that file (quotes are important there too).

    Another option--and I'll leave it to you to research--if you didn't want to give it a filename at all, you could explore using the SET command so it'd do something like always looking for and uploading a file named with today's date. More info here on batch arguments and SET.