批处理变量名中的冒号

Colon in batch variable name

我有一个批处理脚本,它应该可以访问一个名为 env:dev 的变量,所以它里面有一个冒号...这个变量是由第三方组件设置的,所以我不对那个命名没有影响...

如何在我的批处理脚本中访问这个变量的内容?我知道 : 是一个特殊字符,所以我可以逃避它吗?以下无效:

echo %env:dev%
echo "%env:dev%"
echo %env^:dev%
...

有什么建议吗?

如果启用了命令扩展(Windows cmd 默认值),: 冒号在 CMD 环境变量中具有特殊含义,例如

很难 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\so973141.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 /?

The command extensions involve changes and/or additions to the following commands:

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

To get specific details, type commandname /? to view the specifics.