批处理文件用于具有2个数组的循环

时间:2022-02-22 01:02:12

I wish to have the for loop in my batch file to iterate 2 arrays. The pseudo code in my mind is something like below:

我希望在我的批处理文件中使用for循环来迭代2个数组。我脑海中的伪代码如下所示:

for each i in array1 
 print i
 print array2[x++]

array1 and array2 will have the same size.

array1和array2将具有相同的大小。

Will I be able to achieve the same result in batch file? I currently have the following code.

我能否在批处理文件中获得相同的结果?我目前有以下代码。

for %%i in %APP_LIST1% DO (
    %appcmd% add app /site.name:%siteName% /path:/%%i /physicalPath:"d:\Apps\%%i"
)

I would like to use %APP_LIST2% (aka array2) in the same for loop as well.

我想在同一个for循环中使用%APP_LIST2%(aka array2)。

Help please!

请帮助!

1 个解决方案

#1


1  

I am afraid I don't really understand what is your concern about the second array. If you can access one array, you can access any number of arrays in the same way...

恐怕我真的不明白你对第二个阵列有什么顾虑。如果您可以访问一个阵列,则可以以相同的方式访问任意数量的阵列......

Please, note that an array is a "collection of data items that can be selected by indices computed at run-time" as defined in Wikipedia. This way, you may use the same index used in the first array to access the second one; this should work in your case because "array1 and array2 will have the same size".

请注意,数组是“可以通过运行时计算的索引选择的数据项集合”,如*中所定义的。这样,您可以使用第一个数组中使用的相同索引来访问第二个数组;这应该适用于你的情况,因为“array1和array2将具有相同的大小”。

For example:

例如:

@echo off
setlocal EnableDelayedExpansion

rem Create first array
set i=0
for %%a in (apple orange pear) do (
   set /A i+=1
   set fruit[!i!]=%%a
)

rem Create second array
set i=0
for %%a in (red green blue) do (
   set /A i+=1
   set color[!i!]=%%a
)

rem Access both arrays at same time
for /L %%i in (1,1,3) do (
   echo Fruit: !fruit[%%i]!, color: !color[%%i]!
)

For further details on array management in Batch files, see: this post.

有关批处理文件中阵列管理的更多详细信息,请参阅:此文章。

#1


1  

I am afraid I don't really understand what is your concern about the second array. If you can access one array, you can access any number of arrays in the same way...

恐怕我真的不明白你对第二个阵列有什么顾虑。如果您可以访问一个阵列,则可以以相同的方式访问任意数量的阵列......

Please, note that an array is a "collection of data items that can be selected by indices computed at run-time" as defined in Wikipedia. This way, you may use the same index used in the first array to access the second one; this should work in your case because "array1 and array2 will have the same size".

请注意,数组是“可以通过运行时计算的索引选择的数据项集合”,如*中所定义的。这样,您可以使用第一个数组中使用的相同索引来访问第二个数组;这应该适用于你的情况,因为“array1和array2将具有相同的大小”。

For example:

例如:

@echo off
setlocal EnableDelayedExpansion

rem Create first array
set i=0
for %%a in (apple orange pear) do (
   set /A i+=1
   set fruit[!i!]=%%a
)

rem Create second array
set i=0
for %%a in (red green blue) do (
   set /A i+=1
   set color[!i!]=%%a
)

rem Access both arrays at same time
for /L %%i in (1,1,3) do (
   echo Fruit: !fruit[%%i]!, color: !color[%%i]!
)

For further details on array management in Batch files, see: this post.

有关批处理文件中阵列管理的更多详细信息,请参阅:此文章。