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!
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]
}
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
}
other solution:
$a = @("server1", "server2", "server3")
$b = @(121, 453, 565)
$i=0;
$a | %{"{0} load is: {1}" -f $_, $b[$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.