Powershell 7 ->;将结果添加到数组时,函数中的 ForEach -Parallel 不会返回任何内容
我需要在此函数中使用 Powershell 7 并行循环功能,但是当使用 ForEach 循环时,我无法获取结果并将其放入最后的数组中,我不明白为什么。
有什么想法吗?
Function Get-ResponseFromParallelPings($activeHops) {
$ArrayOfObjects = @()
$activeHops | ForEach-Object -Parallel {
$count = 5
$LatencyNumber = 0
$SuccessNumber = 0
$Answer = Test-Connection -count $count -targetname $_.Name -delay 1
foreach ($a in $Answer) {
$LatencyNumber += $a.Latency / $count
if ($a.Status -eq "Success") {
$IncreaseBy = 100 / $count
$SuccessNumber += $IncreaseBy
}
}
$myObject = [PSCustomObject]@{
DestinationIP = $_.Name
AverageLatency = $LatencyNumber
Success = $SuccessNumber
}
$arrayOfObjects += $myObject # <- This line does not work for me.
}
return $arrayOfObjects
}
I need to use Powershell 7 Parallel looping feature in this function but when using ForEach loop, I cannot take the result and put it into the array at the end and I do not undestand why.
Any ideas?
Function Get-ResponseFromParallelPings($activeHops) {
$ArrayOfObjects = @()
$activeHops | ForEach-Object -Parallel {
$count = 5
$LatencyNumber = 0
$SuccessNumber = 0
$Answer = Test-Connection -count $count -targetname $_.Name -delay 1
foreach ($a in $Answer) {
$LatencyNumber += $a.Latency / $count
if ($a.Status -eq "Success") {
$IncreaseBy = 100 / $count
$SuccessNumber += $IncreaseBy
}
}
$myObject = [PSCustomObject]@{
DestinationIP = $_.Name
AverageLatency = $LatencyNumber
Success = $SuccessNumber
}
$arrayOfObjects += $myObject # <- This line does not work for me.
}
return $arrayOfObjects
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的问题是并行运行的线程必须更改同一个数组。有一些方法可以实现这一点,但在这种情况下,只需从函数中发出 $myobject 就足够了。我删除了数组和将 $myObject 添加到数组的代码。
当调用该函数时,会自动创建数组,因此结果是相同的。
The problem here is that threads running in parallel have to alter the same array. There are methods to make that happen, but in this case it is enough to just emit $myobject from the function. I removed the array and the code to add $myObject to the array.
When the function is called the array is created automatically, so the result is the same.