3

I have a batch script which should have access to a variable named something like env:dev, so it has a colon inside... this variable is set by a third-party component, so I don't have influence on that naming...

How can I access the content of this variable in my batch script? I know that : is a special character, so can I perhaps escape it? The following doesn't work:

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

Any suggestions?

1 Answer 1

15

A : colon has special meaning in CMD environment variables if command extensions are enabled (Windows cmd default), for instance

Hard to escape a : colon in variable name, if possible at all. Here's a workaround: create variables with such names that : colon is replaced by another character, e.g. _ Low Line (underscore):

@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

Output:

==> 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

==>

Edit: for the sake of completeness:

@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 

Be aware of disabling command extensions impact, read 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.

1
  • Thanks a lot! Oh man, how can one put : in a variable name... what a mess.
    – Matthias
    Commented Jun 23, 2016 at 18:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.