如何创建一个每次调用时*调用*%date% 或%time% 的用户环境变量?
我正在尝试使用以下定义创建 2 个用户环境变量:
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%
这样每次调用时:
echo %datel%
echo %datetime%
我得到:
20110407
20110407-11_45_45
我可以在 GUI 中毫无问题地定义用户环境变量(计算机->(右键单击)属性->高级系统设置 - >环境变量),当我在新的 cmd 窗口中进行“设置”时,我得到以下信息:
>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%
但是“回显”它们并不是我所期望的:
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%
提前非常感谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
call echo %datel%
会导致另一个解析过程(您在这里需要)。 echo 本身不会扩展任何环境变量,shell 在解析一行时会执行此操作。因此你需要强制这样做。然而,这是没有记录的,所以要持保留态度。更强大(即实际支持)的选项可能是使用子例程:
然后用
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:
and then call it with
或者使用延迟扩展,则可以在一行中扩展两次。
它之所以有效,是因为首先批处理行解析器将
%datel%
扩展为!date:~-4!!date:~3,2!!date:~0,2!
并且在完成百分比扩展之后。然后处理转义字符,然后作为解析器扩展的最后一个阶段,感叹号也被扩展。
cmd.exe 如何解析脚本中进行了解释
Or use the delayed expansion, then you are able to expands two times in one line.
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