开发者

How to create a user Environment variable that *calls* %date% or %time% each time it's invoked?

开发者 https://www.devze.com 2023-02-22 13:25 出处:网络
I\'m trying to create 2 user environment variables with the following defintion: datel=%date:~-4%%date:~3,2%%date:~0,2%

I'm trying to create 2 user environment variables with the following defintion:

datel=%date:~-4%%date:~3,2%%date:~0,2%
datetime=%date:~-4%%date:~3,2%%date开发者_开发问答:~0,2%-%time:~0,2%_%time:~3,2%_%time:~6,2%

so that every time I call:

echo %datel%
echo %datetime%

I get:

20110407
20110407-11_45_45

I can define the user environment variables without problems in the GUI (Computer->(Right Click)Properties->Advanced System Settings->Environment Variables) and when I do a "set" in a new cmd window I get the following:

>set da  
datel=%date:~-4%%date:~3,2%%date:~0,2%
datetime=%date:~-4%%date:~3,2%%date:~0,2%-%time:~0,2%_%time:~3,2%_%time:~6,2%

But then "echoing" them is not what I expected:

C:\Users\jaravj
>echo %datel%
%date:~-4%%date:~3,2%%date:~0,2%

C:\Users\jaravj
>echo %datetime%
%date:~-4%%date:~3,2%%date:~0,2%-%time:~0,2%_%time:~3,2%_%time:~6,2%

Thanks a huge lot in advance.


Use call echo %datel% which results in another parsing pass (which you need here). echo by itself will not expand any environment variables, that does the shell upon parsing a line. Therefore you need to force that.

That's undocumented, however, so take that with a grain of salt. A more robust (i.e. actually supported) option might be to use a subroutine:

:expand
  echo.%*
goto :eof

and then call it with

call :expand echo %datel%


Or use the delayed expansion, then you are able to expands two times in one line.

setlocal
set "datel=!date:~-4!!date:~3,2!!date:~0,2!"
setlocal EnableDelayedExpansion
echo %datel%

It's works because, first the batch line parser expands %datel% to !date:~-4!!date:~3,2!!date:~0,2! and after all percent expansions are done.

Then the escape characters are handled, and then as the last phase the parser expands the exclamations are expanded.

Explained in how cmd.exe parse scripts

0

精彩评论

暂无评论...
验证码 换一张
取 消