0

I have a batch file which is trying to copy a source file to a different directory, but also appending the date and time to the file name. Example command that I have is below.

copy /Y c:\apps\BIDW\Sf_Calls.txt      c:\apps\CDW\SF_CDWCalls_%date:~-4,4%%date:~7,2%%date:~-10,2%_%time:~0,2%%time:~3,2%.txt

However, this command is failing and after some debugging I came to know that time is not parsed correctly. Date gets parsed as 08 for the month, whereas if I run the above command at 7 AM, time is not getting parsed as 07, but only 7 as a result, the destination file name becomes SF_CDWCalls_20180814_ 730 and hence the above copy command is failing with the error message "Invalid Syntax".

Is there a way to get the time as 07:30 using the %time% variable in windows batch file? I see that the time command doesn't support much options.

Balaji Pooruli
  • 198
  • 3
  • 11
  • 1
    Possible duplicate of [How do I get current datetime on the Windows command line, in a suitable format for using in a filename?](https://stackoverflow.com/questions/203090/how-do-i-get-current-datetime-on-the-windows-command-line-in-a-suitable-format) –  Aug 14 '18 at 14:19

1 Answers1

0

Did you happen to notice the whitespace between the last _ and 730 which is caused by the whitespace in the %time% variable? You will see it when running echo %time% a leading space 7:30:23,40

So Conditionally replace the leading space with a 0. This will only affect single digit hh

echo %time: =0%

So in your script, do this:

set tmptime=%time: =0%
copy /Y c:\apps\BIDW\Sf_Calls.txt c:\apps\CDW\SF_CDWCalls_%date:~-4,4%%date:~7,2%%date:~-10,2%_%tmptime:~0,2%%tmptime:~3,2%.txt
Gerhard
  • 18,114
  • 5
  • 20
  • 38
  • Thanks, I will try this. However, what happens when I run the copy command at 11:20 AM? Does it become 01120? I don't want that to happen. – Balaji Pooruli Aug 14 '18 at 13:53
  • 1
    @BalajiPooruli Like I said in my answer, it will only affect single digit `hh` there is no leading space with double digit `hh`, it will still echo `1120` – Gerhard Aug 14 '18 at 13:55
  • 1
    @BalajiPooruli: `%time: =0%` replaces spaces with zeros. For `11:20` that means: no spaces, so no replacements. – Stephan Aug 14 '18 at 14:48