2

I'd like to have log with prepend of time and username, but I haven't been able to get %TIME% and %DATE% to dynamically be evaluated. I've tried many versions of using "!", but I've never gotten it to work. What I'd like is to have

Setlocal EnableDelayedExpansion
set nameDateTime=!%USERNAME% %DATE% %TIME%!
echo %nameDateTime%
echo %nameDateTime%
echo %nameDateTime%
EndLocal

to produce 3 different times (assuming they're done far enough apart). I tried the second answer in: How to create a user Environment variable that *calls* %date% or %time% each time it's invoked?, but when I call echo %date1%, it just prints out date1, while set date1 prints out the whole !date1..! line.

Community
  • 1
  • 1
Dale
  • 333
  • 4
  • 11

1 Answers1

4

Since you already use delayedExpansion:

@echo off
Setlocal DisableDelayedExpansion
set nameDateTime=!USERNAME! !DATE! !TIME!
Setlocal EnableDelayedExpansion
echo %nameDateTime%
echo %nameDateTime%
echo %nameDateTime%
EndLocal

You will need to time space those echos to see they actually print different values

wmz
  • 3,645
  • 1
  • 14
  • 22
  • when I run: echo %nameDateTime% I get !USERNAME! !DATE! !TIME! as the output. – Dale Sep 25 '12 at 20:53
  • 1
    @dale Above work only in batch. Do you want to run it directly from cmd line? – wmz Sep 25 '12 at 20:58
  • no, I don't need it to work on cmd line, just didn't run it that way. – Dale Sep 25 '12 at 20:58
  • Thanks @wmz, it worked, I'm guessing I had stuff that would have worked, I just didn't use a batch file. – Dale Sep 25 '12 at 21:12
  • @dale Another possibility (this would also work from cmd if started with `cmd /v:on`) with delayed expansion enabled, you could escape `!`: `set "nameDateTime=^!USERNAME^! ^!DATE^! ^!TIME^!"` (mind quotes). – wmz Sep 25 '12 at 21:30
  • @wmz Exactly when you use `%username%` it will fail if it contains `!`. With `!username!` it will work always. – jeb Sep 26 '12 at 06:41
  • @jeb You're right I have not thought it well :( Thanks for pointing that out. I will delete it. – wmz Sep 26 '12 at 09:04
  • @dale - Disregard my previous comment, it was wrong I will delete it. See jebs comment (he is correct) – wmz Sep 26 '12 at 09:05