使用批处理脚本复制文件会引发语法错误

copying files using a batch script throws a syntax error

我有以下批处理脚本,当我 运行 它时,它抛出一个错误:

@echo Off
cls
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I

set datetime=%datetime:~0,8%-%datetime:~8,6%

set AGFILE=C:\vendor\My Work\file.txt"
if exist %AGFILE% 
(
echo "file exists"
copy %AGFILE% %AGFILE%.%datetime%
)

当我 运行 脚本时,出现语法错误。如何修复复制部分的语法错误?

你写了

if exist %AGFILE% 
(
echo "file exists"
copy %AGFILE% %AGFILE%.%datetime%
)

但这是语法错误。当 IF 为真时所采取的操作必须与 IF 标记在同一行。这很容易修复:

if exist %AGFILE% (
  echo "file exists"
  copy %AGFILE% %AGFILE%.%datetime%
)

之所以有效,是因为 ( 开始了一个复合语句,只需在与 IF 相同的行开始它就足够了。同样,如果需要在这样的代码中使用ELSE,一般需要在一行中写成) ELSE (