0

I am using this scripts to create a 1 MB file & file name with date & time. And I am using task scheduler for repeat the batch file in every 5 minutes. However, it only successfully create files in 26 April. In 27 April the task is still successfully running but no file is saved in /temp

cd C:\temp echo Start > dummy.txt for /l %%x in (1, 1, 35000) do echo %date% %time% >> C:\temp\dummy.txt COPY dummy.txt %date:~-4,4%%date:~-10,2%%date:~-7,2%-%time:~0,2%%time:~3,2%%time:~6,2%.txt echo End >> dummy.txt 

Debug simple batch scripts

0

    1 Answer 1

    2

    The problem you're seeing is due to delayed expansion, where when you're operating in a loop like this the variables %date% and %time% are determined at the start, and don't update as the script loop runs. You can see that if you echo out your query to screen :

    for /l %%x in (1, 1, 35000) do echo %date% %time% 

    You'll see the time never changes.

    The fix is to enable delayed expansion, and also bracket the loop code (looks like delayed expansion doesn't work otherwise), and finally replace the % variable characters with ! which tells the system they should be re-evaluated each time the loop runs. Tested, and I think this should do the job you're after :

    setlocal ENABLEDELAYEDEXPANSION cd C:\temp echo Start > dummy.txt for /l %%x in (1, 1, 35000) do ( echo !date! !time! >> C:\temp\dummy.txt ) set longHour=%time:~0,2% set hour=%longHour: =0% COPY dummy.txt %date:~-4,4%%date:~-10,2%%date:~-7,2%-%hour%%time:~3,2%%time:~6,2%.txt echo End >> dummy.txt 

    Note, the other issue I spotted is that time:~0,2 only works as you'd expect when you have 2 digit hours (I'd not have noticed if I hadn't happened to try it before 10am!), so for example after 10am it might generate :

    20232904-101735.txt

    but before 10am you'd end up with :

    20232904- 95935.txt

    with a space between the - and 9, so I've also gotten it to replace that space with a 0 if one is found, so you end up with :

    20232904-095935.txt

    1
    • The space is most likely the real problem as described in the answer because of COPY dummy.txt 20232904- 95935.txt results on execution in the error message The syntax of the command is incorrect. It is not possible to specify three file names on one COPY command line without + between the first two file names or enclosing the destination file name containing a space character in ". It is in general always advisable to enclose file/folder names in " even on not needed as the entire argument string does not contain a space or one of these characters &()[]{}^=;!'+,`~.
      – Mofi
      CommentedApr 30, 2023 at 12:35

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.