windows - 批处理变量名中的冒号

标签 windows command-line batch-processing

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

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

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

有什么建议吗?

最佳答案

: 冒号在 CMD 环境变量中有特殊含义,例如,如果命令扩展被启用(Windows 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\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/?:

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.

关于windows - 批处理变量名中的冒号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37973141/

相关文章:

windows - 计算文件中未知字符串最常见的出现次数

windows - 使用命令行开关将 PDF 另存为文本 - 可以做到吗?

command-line - 我如何有选择地要求 Ant 的命令行参数?

shell - 如何从命令行运行SWI-Prolog?

java - 如何使用 JDBC 中的PreparedStatement 在表中存储长值?

batch-file - 将前导零添加到文件名

Java SunPKCS11 通过网络访问 USB 加密 token

windows - 在 PsychoPy 中使用 pyo 时 pythonw.exe 崩溃

mysql - 如何使用命令行将 SQL 查询导出到 TXT

Windows 批处理脚本查找包含字符串或变量具有值的变量