简体   繁体   中英

Using nested foreach in powershell

I am trying to running this by using foreach in powershell.

$var1 = @("aaa","bbb","ccc"..........)
$var2 = @("111","222","333"..........)
 foreach ($val1 in $var1) {
   echo $val1
    foreach ($val2 in $var2) {
       echo $val2
  }
}
Output of the above script is:
aaa
111
222
333
bbb
111
222
333........

But i want to print like this: 
aaa
111
bbb
222
ccc
333........

Is it possible by foreach? I already solve this problem by using for loop.

$var1 = @("aaa","bbb","ccc")
$var2 = @("111","222","333")

$maxCount = [math]::Max($var1.Count,$var2.Count)
  • Using ForEach
foreach($z in 0..($maxCount-1))
{
    $var1[$z]
    $var2[$z]
}
  • Using For
for($i=0;$i -lt $maxCount;$i++)
{
    $var1[$i]
    $var2[$i]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM