1

I'm having trouble access the value stored in the example below. I need to access the value stored in a variable, but the variable name is stored in a different variable. Please help.

Example:

setlocal enabledelayedexpansion

set a222333password=hellopass

for %%i in (%fileserver%\t*) do ( 
  set currentfilename=%%~ni --> file name is "t222333"
  set currentlogin=!currentfilename:t=a!  --> login is "a222333"
  set currentpasswd=!!currentlogin!password! --> password should be "hellopass"
  echo !currentpasswd!  --> this gives me the value "a222333password" instead of "hellopass"

)
reasar
  • 13
  • 2
  • This type of management is explained at [this answer](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990), although the topic is different. – Aacini Jun 22 '17 at 02:43

1 Answers1

2

You cannot nest delayed expansion like set currentpasswd=!!currentlogin!password!, because this first detects !!, which are combined to one opening !, so the variable expansion !currentlogin! is done resulting in a222333, then there is the literal part password, and finally another ! that cannot be paired and is therefore ignored.

However, you could try this, because call initiates another parsing phase:

call set "currentpasswd=%%!currentlogin!password%%"

Or this, because for variable references become expanded before delayed expansion occurs:

for /F "delims=" %%Z in ("!currentlogin!") do set "currentpasswd=!%%Zpassword!"

Or also this, because argument references, like normally expanded variables (%-expansion), are expanded before delayed expansion is done:

rem // Instead of `set currentpasswd=!!currentlogin!password!`:
call :SUBROUTINE currentpasswd "!currentlogin!"

rem // Then, at the end of your current script:
goto :EOF

:SUBROUTINE
set "%~1=!%~2password!"
goto :EOF

rem // Alternatively, when you do not want to pass any arguments to the sub-routine:
:SUBROUTINE
set "currentpasswd=!%currentlogin%password!"
goto :EOF

All these variants have got two important things in common:

  1. there occur two expansion phases;
  2. the inner variable reference is expanded before the outer one;
aschipfl
  • 33,626
  • 12
  • 54
  • 99