0

enter image description here

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!!

user18209625
  • 139
  • 2
  • 15
  • It is indeed possible, and the answer shows you how. If the solution provided there doesn't work (for you), please provide feedback. – mklement0 May 17 '23 at 22:46

1 Answers1

0

First things first: the usual recommendation applies:

  • It's better to use a native PowerShell solutions, such as 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.

mklement0
  • 382,024
  • 64
  • 607
  • 775