使用VBA运行WinSCP脚本

我能够通过使用以下代码在CMD窗口中从SFTP下载文件:

 WinSCP.com # Connect to the host and login using password open user:pw@address # get all the files in the remote directory and download them to a specific local directory lcd C:\Users\xx\Desktop get *.xlsx # Close and terminate the session exit 

我在网上search,发现我可以把这些代码放在bat文件中并使用

 Call Shell("cmd.exe /c C:\Users\xx\Desktop\WinSCPGet.bat", 1) 

但是,只有bat文件的第一行WinSCP.com正在执行。 它会popupcmd窗口,显示这个,没有做任何事情。 在这里输入图像说明

如何一次执行所有的行?

谢谢

您拥有的代码不是Windowsbatch file。 这是一个Windows命令,其次是WinSCP命令。 第一个命令运行winscp.com应用程序,然后坐等待input。 如果最终closures它,Windows命令解释程序( cmd.exe )将继续执行其余的命令,失败的最多,因为它们不是Windows命令。 另请参阅WinSCP脚本不在batch file中执行 。

因此,您必须将命令( open exit )保存到WinSCP脚本文件(比如script.txt ),然后使用/script开关执行/script

 Call Shell("C:\path\winscp.com /ini=nul /script=c:\path\script.txt") 

或者,使用/command开关在WinSCP命令行中指定所有命令:

 Call Shell("C:\path\winscp.com /ini=nul /command ""open user:pw@address"" ""lcd C:\Users\xx\Desktop"" ""get *.xlsx"" ""exit""") 

关于引号:使用/command开关,您必须将每个命令括在双引号中。 在VBAstring中,要使用双引号,您必须通过加倍将其转义。

另请注意,通常应使用/ini=nul开关来隔离从WinSCPconfiguration运行的WinSCP脚本 。 这样你也可以确保脚本将在其他机器上运行。 您的脚本不会,因为它缺less-hostkey开关来validationSSH主机密钥指纹 。 使用/ini=nul将帮助你意识到这一点。

您可以让WinSCP GUI为您生成完整的命令行 (包括-hostkey )。

另请参阅使用WinSCP自动将文件传输到SFTP服务器 。

我喜欢这个小而紧凑的程序,并将其用在我自己的项目中。 不需要临时文件。 快速可靠。

将一个stringsrc (绝对path)parsing为uploadImageByFTP 。 等等C:\ Users \ user \ Desktop \ image.jpg,文件将被上传。

更换:

  • 与FTP用户<username>
  • 使用FTP密码的<password>
  • 带有FTP主机名的<hostname> (例如example.com)
  • <WinSCP.com path> ,WinSCP客户端(如C:\ Program Files文件(x86)\ WinSCP \ WinSCP.com。) 注意WinSCP.com而不是WinSCP.exe
  • 在你的FTP客户端上有<FTP-path>path(etc / httpdocs / wp-content / uploads)

  Sub uploadImageByFTP(src As String) Dim script As Object: Set script = VBA.CreateObject("WScript.Shell") Dim waitOnReturn As Boolean: waitOnReturn = True Dim windowStyle As Integer: windowStyle = 1 'Not empty If (src <> vbNullString) Then 'Execute script script.Run _ """<WinSCP.com path>"" " + _ "/ini=nul " + _ "/command " + _ """open ftp://<username>:<password>@<hostname>/"" " + _ """cd <FTP-path>"" " + _ """put " & """""" & src & """""" & """ " + _ """close"" " + _ """exit""", windowStyle, waitOnReturn End If End Sub 

WScript.Shell比默认的Shell()更强大,因为你可以附加一个waitOnReturn命令; 这告诉VBA,在file upload到FTP服务器之前,不允许进一步的执行。

windowStyle更改为0,如果您不喜欢在每次执行时打开命令提示符。