问题描述
我无法访问下面示例中存储的值.我需要访问存储在变量中的值,但是变量名称存储在其他变量中.请帮忙.
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.
示例:
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"
)
推荐答案
您不能像 set currentpasswd = !! currentlogin!password!
那样嵌套延迟扩展,因为它首先检测到 !!
,它们组合成一个打开的!
,因此完成了变量扩展!currentlogin!
的操作,生成了 a222333
,然后是文字部分 password
,最后是另一个!
无法配对,因此将被忽略.
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.
但是,您可以尝试执行此操作,因为 call
会启动另一个解析阶段:
However, you could try this, because call
initiates another parsing phase:
call set "currentpasswd=%%!currentlogin!password%%"
或者这是因为 for
变量引用在延迟扩展发生之前已被扩展:
Or this, because for
variable references become expanded before delayed expansion occurs:
for /F "delims=" %%Z in ("!currentlogin!") do set "currentpasswd=!%%Zpassword!"
还是这样,因为参数引用像正常扩展的变量(%
-expansion)一样,在延迟扩展完成之前被扩展了:
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:
- 有两个扩展阶段;
- 内部变量引用在外部变量引用之前展开;
这篇关于批处理脚本-如何使用存储了变量名称的其他变量获取变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!