If you want to mimic the Exact output of the ping command in a console, then the easiest way would be:
$temp = New-TemporaryFile
ping 8.8.8.8 > $temp.FullName
$result = $temp | Get-Content -Raw
$temp | Remove-Item -Force
# Output on screen
$result
However, if you want to get this exact same output style using the Test-Connection
cmdlet, there's a lot more work to be done.
Here's a function that outputs like the ping
command would do:
function Format-TestConnection {
# mimic the **Exact** output of the ping command using Test-Connection
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[string]$ComputerName,
[int]$Count = 4
)
# build output
$sb = New-Object -TypeName System.Text.StringBuilder
[void]$sb.AppendLine("Pinging $ComputerName with 32 bytes of data:")
# perform Test-Connection and capture the results
$success = 0
$responseTimes = @()
for ($i = 0; $i -lt $count; $i++) {
$startTime = (Get-Date).Millisecond
try {
$ping = Test-Connection -ComputerName $ComputerName -Count 1 -BufferSize 32 -ErrorAction Stop
[void]$sb.AppendFormat("Reply from {0}: bytes={1} time={2} TTL={3}",
$ComputerName, $ping.ReplySize, $ping.ResponseTime, $ping.TimeToLive)
[void]$sb.AppendLine()
$success++
$responseTimes += $ping.ResponseTime
}
catch {
[void]$sb.AppendLine("Request timed out.")
$responseTimes += ($startTime - (Get-Date).Millisecond)
}
}
[void]$sb.AppendLine()
[void]$sb.Append("Ping statistics for $ComputerName")
[void]$sb.AppendLine(":")
$lost = $Count - $success
$pct = '{0:N0}%' -f (($lost / $Count) * 100)
[void]$sb.Append(" Packets: Sent = $Count, Received = $($success), Lost = $lost ($pct loss)")
if ($success) {
[void]$sb.AppendLine(",")
[void]$sb.AppendLine("Approximate round trip times in milli-seconds:")
$min = [int]($responseTimes | Measure-Object -Minimum).Minimum
$max = [int]($responseTimes | Measure-Object -Maximum).Maximum
$avg = [int]($responseTimes | Measure-Object -Average).Average
[void]$sb.AppendFormat(" Minimum = {0}ms, Maximum = {1}ms, Average = {2}ms", $min, $max, $avg)
[void]$sb.AppendLine()
}
else {
[void]$sb.AppendLine(".")
}
# return the formatted output
$sb.ToString()
}
# use the above function like
Format-TestConnection -ComputerName "8.8.8.8" -Count 4
Output on screen:
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=8 TTL=80
Reply from 8.8.8.8: bytes=32 time=7 TTL=80
Reply from 8.8.8.8: bytes=32 time=7 TTL=80
Reply from 8.8.8.8: bytes=32 time=8 TTL=80
Ping statistics for 8.8.8.8:
Packets: Sent = 4, Received = 4, Lost = 0 (0,00% loss),
Approximate round trip times in milli-seconds:
Minimum = 7ms, Maximum = 8ms, Average = 8ms
If this is NOT what you are asking for, then please EDIT your question and show us the desired output, because the question is unclear about that.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…