The syntax of the command is incorrect when not run from cmd line
batch-file, cmd, for-loop, syntax, task
Solution
Your code cannot be working properly, even from the command line.
Your problem is your setting of `tempfile` and expansion of `%tempfile%` from within the same block of code. The value is expanded when the line is parsed, and all lines of the FOR statement are parsed in one pass. So your IF and REN statements are seeing the value that existed prior to entry of the loop.
Your code fails with a syntax error when `tempfile` is not defined. After expansion, the IF statement becomes invalid: `if exist ( ...`, hence the error.
The reason you think it works from the command line is because you probably ran the code once and it failed, but when finished, the `tempfile` variable is set, so the script will appear to run OK the next time you run it.
Normally I recommend the use of delayed expansion to enable setting and expanding a variable within a loop. But you don't have any reason to use `tempfile` at all - just use the FOR variable directly.
@echo off
del mic_car*.txt
ftp -i -s:car_ftp_script.txt
for /F %%I in ('dir /b/os mic_car*.txt') do (
echo %%I
if exist "%%I" (
del car_report.txt
ren "%%I" car_report.txt
)
)
del mic_car*.txt
copy /y car_report.txt ..\car_report.txt
pause
Actually, I don't understand why you need IF at all since your FOR loop only returns existing files. And all mic_car*.txt files will have been renamed car_report.txt (last one wins), so there should not be any need for your final DEL command.
You can combine the DEL and REN commands into one command by using MOVE
@echo off
del mic_car*.txt
ftp -i -s:car_ftp_script.txt
for /F %%I in ('dir /b/os mic_car*.txt') do (
echo %%I
move /y "%%I" car_report.txt >nul
)
copy /y car_report.txt ..\car_report.txt
pause
Problem
I have a batch file that runs fine if I run it from the command prompt, but throws an error if it's called from Task Scheduler or run through Explorer. It appears that the syntax error occurs with the FOR logic. ``` @echo off del mic_car*.txt ftp -i -s:car_ftp_script.txt pause for /F %%I in ('dir /b/os mic_car*.txt') do ( echo %%I pause set tempfile=%%I if exist %tempfile% ( del car_report.txt ren %tempfile% car_report.txt ) ) del mic_car*.txt copy /y car_report.txt ..\car_report.txt pause ``` If I run this from explorer or Task Scheduler, I see the files being transferred via FTP, followed by the syntax error. If I run it via command line, I see the echo of each file being processed and the largest file is copied to the higher level directory.