将过滤器应用于 Test-NetConnection 结果管道

Apply filter to Test-NetConnection result pipeline

我正在尝试使用 PowerShell 创建简单的“ping”作业。我想以“流水线”的方式来做。尽管看起来 Where-Object 接收字符串,而不是 TestNetConnectionResult class 的对象。能否请您解释一下如何过滤掉 ping 成功的 Test-NetConnection 结果?

Get-Content .\adresses.txt | Test-NetConnection | Where-Object { $_.PingSucceeded } | Write-Output
function megaPing {
    [CmdletBinding()]
    Param(
        [Parameter(ValueFromPipeline, Mandatory, Position = 0)]
        [string]$serverName
    )
    process {
        , [PSCustomObject]@{
            serverName    = $serverName
            PingSucceeded = (Test-NetConnection $serverName).PingSucceeded
        }
    }
}

"127.0.0.1", "127.0.0.2" | megaPing 

你需要使用管道

过滤器工作正常,但您需要一个最终的 ForEach-Object 来处理管道中的结果。

Get-Content .\adresses.txt `
    | Test-NetConnection `
    | Where-Object { $_.PingSucceeded } `
    | ForEach-Object { Write-Host "SUCCEDED: $($_.ComputerName)" } 

注意:如果您还想忽略来自 Test-NetConnection 的警告,请检查 this question

这是另一种方法:

Get-Content -Path '.\adresses.txt' | Test-NetConnection | 
    Select-Object @{Name = 'Address'; Expression = {$_.ComputerName}},
                  @{Name = 'PingSucceeded'; Expression = {$_.PingSucceeded}}

如果您不想要进度条,请执行以下操作:

$oldProgress = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'

Get-Content -Path '.\adresses.txt' | Test-NetConnection | 
    Select-Object @{Name = 'Address'; Expression = {$_.ComputerName}},
                  @{Name = 'PingSucceeded'; Expression = {$_.PingSucceeded}}

$ProgressPreference = $oldProgress

结果类似于

Address      PingSucceeded
---------    -------------
127.0.0.1             True
10.10.2.153          False

忽略警告?无论如何警告都不会将对象放入管道中。

echo yahoo.com microsoft.com | set-content addresses.txt
Get-Content addresses.txt | Test-NetConnection -WarningAction SilentlyContinue | 
  Where PingSucceeded


ComputerName           : yahoo.com
RemoteAddress          : 74.6.231.20
InterfaceAlias         : Wi-Fi
SourceAddress          : 192.168.1.114
PingSucceeded          : True
PingReplyDetails (RTT) : 61 ms