使用VBA运行WinSCP脚本

New*_*sIn 4 excel vba cmd winscp

我可以CMD使用以下代码从Windows中的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
Run Code Online (Sandbox Code Playgroud)

我在线搜索,发现可以将这些代码放在bat文件中并使用

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

但是,仅WinSCP.com执行bat文件的第一行。它将弹出cmd窗口,显示此内容,而不执行其他任何操作。 在此处输入图片说明

如何一次执行所有行?

谢谢

Mar*_*ryl 5

您拥有的代码不是Windows批处理文件。这是一个Windows命令,后跟WinSCP命令。第一个命令运行winscp.com应用程序,然后它坐下来等待输入。如果最终关闭它,则Windows命令解释器(cmd.exe)将继续执行其余大多数命令,因为它们不是Windows命令。另请参见WinSCP脚本未在批处理文件中执行和WinSCP常见问题解答为什么在批处理文件中指定的某些WinSCP脚本命令未执行/失败?

因此,您必须将命令(opento exit)保存到WinSCP脚本文件(例如script.txt),然后使用/scriptswitch执行脚本:

Call Shell("C:\path\winscp.com /ini=nul /script=c:\path\script.txt")
Run Code Online (Sandbox Code Playgroud)

或者,使用/commandswitch在WinSCP命令行上指定所有命令:

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

关于引号:使用/command开关时,必须将每个命令都用双引号引起来。在VBA字符串中,要使用双引号,必须将其加倍以对其进行转义。

还要注意的是,你通常应该使用/ini=nul开关了WinSCP赋予脚本运行从您的WinSCP配置隔离。这样,您还可以确保脚本将在其他计算机上运行。您的脚本不会,因为它缺少的-hostkey开关,以验证SSH主机密钥指纹。使用/ini=nul可以帮助您意识到这一点。

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

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