Search code examples
batch-filebatch-processingbatch-rename

Set the filename to date in batch


So I have the idea of creating a logfile based on the date of the creation. I have to do this in batch. My code so far:

@echo off
>log.txt (
cd %~dp0
echo [%DATE%] [%TIME%] [%USERNAME%] : Test
)
pause 

How can I do this?. If I set the filename to %DATE%.log I get an error. Can I do this with some kind of SET filename=%DATE%? But then I have to use %filename%.log and I doubt this will work.


Solution

  • %DATE% returns (e.g. Tue 08/18/2015), since we can't rename/set a file name with "/" character inside, so replace the forward slash with an empty character like:

    set Valid_DATE=%DATE:/=%
    

    Then you simple replace [%DATE%] with [%Valid_DATE%]