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

主宰稳场 提交于 2019-12-07 21:44:48

问题


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.


回答1:


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%



回答2:


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



来源:https://stackoverflow.com/questions/5579213/how-to-create-a-user-environment-variable-that-calls-date-or-time-each-tim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!