Powershell中的数组 - 无法通过与第二个数组对应来读取每个值

问题描述

我正在做一个项目,

我有 3 个数组,我想从中获取所有值。也许一些代码比解释更好。

$Array1= "Value1","Value2",....
$Array2= "Another1","Another2",...
$Array3= "Again1","Again2",...

我的结果应该是

Value1 Another1 Again1
Value2 Another2 Again2

等等...

我尝试了很多这样的选择:

foreach($i in $Array1){
  Foreach($j in $Value2){
     Write-host $i "," $j
   }
} 

result:
Value1,Another1
Value1,Another2
Value2,Another1
Value2,Another2

我已经搜索了大约 5 个小时的解决方案。而且我不是 powershell 专家。 请帮帮我!!

解决方法

您需要确保所有数组都具有相同数量的元素,或者使用最少数量的元素进行循环:

$Array1= "Value1","Value2" #
$Array2= "Another1","Another2"#
$Array3= "Again1","Again2"#

# make sure you do not step out of index on one of the arrays
$items = [math]::Min($Array1.Count,[math]::Min($Array2.Count,$Array3.Count))

for ($i = 0; $i -lt $items; $i++) {
    # using the -f Format operator gives nice-looking code I think
    '{0},{1},{2}' -f $Array1[$i],$Array2[$i],$Array3[$i]
}

结果:

Value1,Another1,Again1
Value2,Another2,Again2