Powershell 7 -> ForEach - Parallel in a Function does not return anything when the result is added to the array

Powershell 7 -> ForEach -Parallel in a Function does not return anything when the result is added to the array

我需要在此函数中使用 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
}

这里的问题是并行的线程 运行 必须改变同一个数组。有一些方法可以做到这一点,但在这种情况下,只需从函数中发出 $myobject 就足够了。我删除了数组和将 $myObject 添加到数组的代码。

函数调用时自动创建数组,所以结果是一样的。

Function Get-ResponseFromParallelPings($activeHops) {
    $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 
        }
        $myObject
    }
}