我无法访问下面示例中存储的值。我需要访问存储在变量中的值,但变量名称存储在不同的变量中。请帮忙。
示例:
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"
)
答案 0 :(得分:2)
您无法嵌套set currentpasswd=!!currentlogin!password!
之类的延迟展开,因为它首先检测到!!
,它们合并为一个开头!
,因此变量展开!currentlogin!
已完成a222333
,然后是文字部分password
,最后是另一个!
,无法配对,因此会被忽略。
但是,你可以试试这个,因为call
启动了另一个解析阶段:
call set "currentpasswd=%%!currentlogin!password%%"
或者这样,因为for
变量引用在延迟扩展发生之前变得扩展:
for /F "delims=" %%Z in ("!currentlogin!") do set "currentpasswd=!%%Zpassword!"
或者也是这样,因为参数引用(如通常扩展的变量(%
- 扩展))在延迟扩展完成之前会被扩展:
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
所有这些变体都有两个重要的共同点: