问题
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"
)
回答1:
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:
- there occur two expansion phases;
- the inner variable reference is expanded before the outer one;
来源:https://stackoverflow.com/questions/44687709/batch-script-how-to-get-variable-value-using-a-different-variable-that-has-the