Properly timestamp a log file created by batch script

10,822

This is because cmd expands variables when a statement is parsed not directly prior to execution. A statement in this case is the complete for including the block after it. So all that remains within the for loop are literal strings, no variables.

You can use delayed expansion to correct the issue. Put the following at the start of your batch:

setlocal enabledelayedexpansion

and then use !date! and !time! within the loop. This will expand the variables just prior to executing a statement and thus will work as intended.

Share:
10,822
Admin
Author by

Admin

Updated on July 12, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to create a log file with timestamps of events that are taking place in a batch file.

    As you can see from the code below, I am not an expert when it comes to writing a batch file. The process works as it should, although the technique is very poor. In order to keep the batch file from deleting itself, I set it to read-only. I'll get around to figuring out how to exclude the batch file at some point. Right now that isn't as important.

    @echo off
    echo Compressing Files...
    echo Compression Batch File STARTED: %date% %time% >> c:\temp\backup-compress.log
    echo --------------------------------------------- >> c:\temp\backup-compress.log
    for %%X in (*) do ( 
        "c:\Program Files\7-Zip\7z.exe" a -tgzip "%%X.gz" "%%X"
        echo %%X Compressed: %date% %time:~-11,8% >> c:\temp\backup-compress.log
        echo Deleting: %%X
        del "%%X"
        echo %%X Deleted: %date% %time:~-11,8% >> c:\temp\backup-compress.log
        )
    echo Moving compressed copies to Compressed Backups folder...
    move *.gz "Compressed Backups\" > NUL
    echo --------------------------------------------- >> c:\temp\backup-compress.log
    echo Compression Batch File FINSHED: %date% %time% >> c:\temp\backup-compress.log
    echo Compression completed successfully...
    echo
    

    The resulting log file looks exactly how I want it to, however, the time stamp and date remain constant throughout the log. Rather than an updated time stamp as events occur in the batch file, I only see the time and date that the batch file was started in place of every %time% and %date% instance.

    How can I correct this problem and see the right time and date stamps for the log file that I am creating?

    PS: Forgive me for the length of this post and what is likely a simple problem to solve. Also, if the tags are not quite right, I apologize, this is my first time actually posting a question, although the site has always been a great resource for answers.