在PowerShell中使用Threading.Tasks-有时会出现意外结果

在PowerShell中使用Threading.Tasks-有时会出现意外结果,powershell,asynchronous,Powershell,Asynchronous,我有一个脚本,其中包含一个函数,该函数使用任务扫描一系列IP,当在我的笔记本电脑上使用它(Windows 10 x64和Powershell 5.1.18362.1110)时,它似乎运行得很快且可靠 function Test-ConnectionAsync { # Uses Async function to check which hosts in a range respond to ICMP Param ( [string[]]$targets,

我有一个脚本,其中包含一个函数,该函数使用任务扫描一系列IP,当在我的笔记本电脑上使用它(Windows 10 x64和Powershell 5.1.18362.1110)时,它似乎运行得很快且可靠

function Test-ConnectionAsync {
    # Uses Async function to check which hosts in a range respond to ICMP
    Param (
        [string[]]$targets,
        [int]$timeout = 1000 # Default timeout of 1 second because high latency is to be expected
    )

    $Task = ForEach ($target in $targets) {
        ([System.Net.NetworkInformation.Ping]::new()).SendPingAsync($target,$timeout)
    }

    Try { [Threading.Tasks.Task]::WaitAll($Task) }
    Catch {}

    $alive = $Task | ForEach-Object {
        If ($_.Result.Status -eq "Success") {
            $_.Result.Address.ToString()
        }
    }

    $alive
}
但是,我最近开始在Server2012系统(Powershell 5.1.14409.1018)上测试此功能,有时返回的列表包含重复条目(在我的笔记本电脑上没有发生这种情况)。当更改代码以使其始终返回IP(删除“If($\ Result.Status-eq“Success”))时,我注意到以下输出:

10.14.165.1
10.14.165.2
0.0.0.0
...
0.0.0.0
10.14.165.126
10.14.165.2
0.0.0.0
...
我在这里扫描范围10.14.164.1-10.14.165.254,如果10.14.165.126下面的行有响应,则应包含10.14.165.127,如果没有响应,则应包含0.0.0.0。 但行是重复的10.14.165.2条目?为什么会发生这种情况?我该如何预防

编辑-调用函数:

using namespace System.Collections.Generic
$iplist = [List[string]]::new()
...
$octets = $store.SubnetBO.Split(".")
$prefix = "{0}.{1}" -f $octets[0], $octets[1]
[int]$firstoctet3 = $octets[2]
$lastoctet3 = $firstoctet3 + $store.SubnetSize - 1

$iplist.AddRange([string[]]($firstoctet3..$lastoctet3 | ForEach-Object {$octet3 = $_; 1..254 | ForEach-Object {"$prefix.$octet3.$_"}}))
$aliveips = Test-ConnectionAsync $iplist

您没有显示如何定义问题最可能出现的
$Targets
。请添加调用“Test ConnectionAsync”函数的部分。感谢您的帮助。它是通用的。列表,为清晰起见添加了代码。我确信$iplist不包含重复项。我已经通过将$iplist和$aliveips并排进行了测试,当$iplist[$I]为“10.14.165.126”时,对应的条目$aliveips[$I]包含“10.14.165.2”