Reputation: 55
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.
Upvotes: 3
Views: 11060
Reputation: 2342
I use a little different method for getting proper times, because I don't care about the miliseconds.
I set my time like this:
FOR /F %%A IN ('TIME/T') DO SET timeEdit=%%A
ECHO %timeEdit%
This way I get the time the way I want it, the only downfall is that this is a bit longer than the setlocal method. You would need both lines if you wanted to capture multiple times, because you are hard-setting a variable for the Time, not capturing the time from the system in realtime.
Upvotes: 0
Reputation: 354526
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.
Upvotes: 4