我有一个批处理脚本,它应该可以访问一个名为env:dev
的变量,所以它里面有一个冒号...这个变量是由第三方组件设置的,所以我没有对命名的影响...
如何在批处理脚本中访问此变量的内容?我知道:
是一个特殊的角色,所以我可以逃避它吗?以下不起作用:
echo %env:dev%
echo "%env:dev%"
echo %env^:dev%
...
有什么建议吗?
答案 0 :(得分:7)
:
冒号在CMD
环境变量中具有特殊含义,如果启用了命令扩展(Windows cmd
默认值),例如
%variable:StrToFind=NewStr%
%variable:~num_chars_to_skip%
%variable:~num_chars_to_skip,num_chars_to_keep%
变量名称很难escape :
个冒号, ,如果可能的话 。这是一个解决方法:创建具有这样名称的变量,:
冒号被另一个字符替换,例如_
低线(下划线):
@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
rem create sample variables
set "env:dev1=some thing!" value contains exclamation mark
set "env:dev2=some thing%%" value contains percent sign
set "an:other=some:thing3" another name containing colon
echo --- before ---
set env
set an
for /F "tokens=1* delims==" %%G in ('set') do (
set "auxName=%%G"
set "auxValue=%%H"
call :colons
)
echo --- after ---
set env
set an
rem
ENDLOCAL
goto :eof
:colons
if not "%auxName::=_%" == "%auxName%" set "%auxName::=_%=%auxValue%"
goto :eof
<强>输出强>:
==> d:\bat\so\37973141.bat
--- before ---
env:dev1=some thing!
env:dev2=some thing%
an:other=some:thing3
--- after ---
env:dev1=some thing!
env:dev2=some thing%
env_dev1=some thing!
env_dev2=some thing%
an:other=some:thing3
an_other=some:thing3
==>
修改:为了完整起见:
@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
rem create sample variables
set "env:dev1=some thing!" value contains exclamation mark
set "env:dev2=some thing%%" value contains percent sign
set "an:other=some:thing3" another name containing colon
rem use sample variables
SETLOCAL DisableExtensions
echo Disabled Extensions %env:dev1% / %env:dev2% / %an:other%
ENDLOCAL
请注意禁用命令扩展的影响,请阅读cmd /?
:
命令扩展涉及对的更改和/或添加 以下命令:
DEL or ERASE COLOR CD or CHDIR MD or MKDIR PROMPT PUSHD POPD SET SETLOCAL ENDLOCAL IF FOR CALL SHIFT GOTO START (also includes changes to external command invocation) ASSOC FTYPE
要获取具体细节,请键入commandname /?查看细节。