如何跨ENDLOCAL返回值数组

问题描述 投票:1回答:2

我有两个可变长度值的数组,TargetName []和TargetCpu [],我需要在ENDLOCAL边界返回。我尝试了以下内容,但只返回第一个数组的第一个值。

for /L %%i in (0,1,%MaxIndex%) do (
    for /f "delims=" %%j in (""!TargetName[%%i]!"") do (
        for /f "delims=" %%k in (""!TargetCpu[%%i]!"") do (
            endlocal
            set TargetName[%%i]=%%j
            set TargetCpu[%%i]=%%k
        )
    )
)

下面是返回值的打印。

Number Targets: 3
TargetName[0]: "Computer1"
TargetCpu[0] : "x64"
TargetName[1]: "!TargetName[1]!"
TargetCpu[1] : "!TargetCpu[1]!"
TargetName[2]: "!TargetName[2]!"
TargetCpu[2] : "!TargetCpu[2]!"

我已经阅读了我能找到的所有内容,但我尝试过的任何可变长度数组都没有。

arrays batch-file return
2个回答
2
投票
@echo off
setlocal

set "MaxIndex=6"
call :CreateArrays
set TargetName
set TargetCPU
goto :EOF


:CreateArrays

setlocal EnableDelayedExpansion
for /L %%i in (1,1,%MaxIndex%) do (
   set /A TargetName[%%i]=!random!, TargetCpu[%%i]=!random!
)

rem Return the arrays to the calling scope
set "currentScope=1"
for /F "delims=" %%a in ('set TargetName[ ^& set TargetCPU[') do (
   if defined currentScope endlocal
   set "%%a"
)
exit /B

1
投票
set target>tempfile
rem insert your endlocal here
for /f "delims=" %%a in (tempfile) do set "%%a"
set target

第一个set将列出所有将target启动到tempfile中的变量名称。

然后执行你的endlocal

然后读取文件的每一行,其格式为name=value,并以set关键字为前缀执行。

最终的set将显示结果。

清理临时文件是你的事。当然,如果你有其他你想要恢复的元素,你可以使用

set targetname>>tempfile
set targetcpu>>tempfile
© www.soinside.com 2019 - 2024. All rights reserved.