2

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.

2
  • It's doable with a for loop at first glance Commented Jul 30, 2021 at 16:01
  • I already solved this problem by using for loop. Can you help by using foreach with condition? Commented Jul 30, 2021 at 16:03

1 Answer 1

1
$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]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Nice; as an aside: I proposed enhancing PowerShell to support the following syntax (which would support an open-ended number of collections to iterate over in tandem), but it was declined: foreach ($val1, $val2 in $var1, $var2) { ... } - see GitHub issue#14732).
@mklement0 would have been a great addition actually. feels bad.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.