Batch Script - How to get variable value using a different variable that has the variable name stored

这一生的挚爱 提交于 2020-01-05 03:54:47

问题


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:

  1. there occur two expansion phases;
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!