How can I store the average round trip time and the package loss in separate variables? I do not want to store the whole ping result. The output should just be:
In this case I want the output to be:
0% loss, 14 ms
Is this possible? THANKS!!
How can I store the average round trip time and the package loss in separate variables? I do not want to store the whole ping result. The output should just be:
In this case I want the output to be:
0% loss, 14 ms
Is this possible? THANKS!!
First things first: the usual recommendation applies:
Test-NetConnection
, which provides objects as output, whose properties you can access, which is both conceptually clearer and more robust than parsing what is invariably text output from external programs.You can use a switch
statement with its -Regex
option:
$lossPercent, $avgPingTime =
switch -regex (ping 8.8.8.8) {
'(\d+)%' { [int] $Matches.1 }
'Average = (\d+)ms' { [int] $Matches.1 }
}
"$lossPercent% loss, $avgPingTime ms"
Note: $avgPingTime
will be $null
if no ping attempt succeeded.
It looks like $LASTEXITCODE -eq 1
returning $true
indicates this condition too.