如何解决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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。