0

I don't understand why it loops badly.

$a = @("server1", "server2", "server3")
$b = @(121, 453, 565)
foreach ($element in $a) {
  foreach ($element2 in $b) {
    Write-Host $element " load is: " $element2
  } 
}

Output:

server1  load is:  121
server1  load is:  453
server1  load is:  565
server2  load is:  121
server2  load is:  453
server2  load is:  565
server3  load is:  121
server3  load is:  453
server3  load is:  565

I expect the following output:

server1 load is: 121
server2 load is: 453
server3 load is: 565

I don't understand how can I fix it. Thanks!

2
  • 3
    Because you have a foreach loop inside a foreach loop, hence 3 * 3 = 9 lines. Commented Nov 10, 2017 at 15:27
  • So I should use a for loop instead. Thank you very much. It makes sense. Commented Nov 10, 2017 at 15:32

3 Answers 3

2

You have a foreach loop inside a foreach loop, hence you're getting 3 * 3 = 9 lines.

The correct way to do what you want is to refer to the array by index.

$a = @("server1", "server2", "server3")
$b = @(121, 453, 565)
for ($i=0; $i -lt $a.length; $i++) 
{ 
  write-host $a[$i] load is: $b[$i] 
}
Sign up to request clarification or add additional context in comments.

Comments

0

You have a 3 element loop nested inside a 3 element loop hence why you are getting 9 results. What you want to do is step through both arrays simultaneously.

$a = @("server1", "server2", "server3")
$b = @(121, 453, 565)

for($index = 0; $index -lt $a.Count;$index++){
    Write-Host "$($a[$index]): $($b[$index])"
}

or

0..($a.Count - 1) | Foreach-Object{
    Write-Host $a[$_]: $b[$_]
}

Both of those solutions assume that $a and $b have the same number of elements. By default requesting a non-existent is not an error in PowerShell. A $null would be returned.

For how you are treating these you would be better of with at minimum a hashtable. This would be structured better and remove some potential failure points. Then you can iterate over each key value pair in one loop

$a = @{
    "server1"= 121
    "server2"= 453
    "server3"= 565
}

$a.GetEnumerator() | ForEach-Object{
    Write-Host $_.Key": " $_.value
}

Comments

0

other solution:

$a = @("server1", "server2", "server3")
$b = @(121, 453, 565)
$i=0;
$a | %{"{0} load is: {1}" -f $_, $b[$i++]}

Comments

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.