批处理文件中的某些 WinSCP 命令不起作用

Some WinSCP commands in a batch file are not working

我正在尝试将文件从 SFTP 服务器下载到我的本地计算机,并使用 WinSCP 创建了一个按日期排列的文件夹。但它正在下降 lcd.

这是我的脚本。

@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%```

这是日志中的错误:

> 2021-03-18 09:17:10.392 lcd D:\Test032021\
< 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

我尝试了很多选项,但仍然失败。非常感谢任何建议指针。

此致, 阿尼卢达

您问题中的批处理文件无法产生您描述的错误。它甚至不会将 lcd 传递给 WinSCP,因为您的批处理文件语法错误。

当你想将批处理文件中的一个命令分成多行时,你需要以 ^ 结束每一行,并且下一行需要缩进。

  • 您的空行不以 ^ 结尾(就像 openlcd 命令之间的空行一样)
  • None 的续行缩进了。

这应该有效:

"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"

查看 WinSCP 常见问题解答 Why are some WinSCP scripting commands specified in a batch file not executed/failing?