如何通过PowerShell获取Ping日志

时间:2019-08-20 05:16:48

标签: powershell

我还是PowerShell的新手,

请问如何编写脚本以ping IP地址获得结果?

&我正在使用 Test-Connection 命令。

enter image description here

5 个答案:

答案 0 :(得分:6)

如果您要在控制台中模拟ping命令的 Exact 输出,那么最简单的方法是:

Math.abs(value - target) < threshold

但是,如果您想使用$temp = New-TemporaryFile ping 8.8.8.8 > $temp.FullName $result = $temp | Get-Content -Raw $temp | Remove-Item -Force # Output on screen $result cmdlet获得完全相同的输出样式,则还有很多工作要做。 这是一个类似于Test-Connection命令输出的函数:

ping

屏幕输出:

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

如果这不是您要的,请EDIT,并向我们显示所需的输出,因为问题尚不清楚。

答案 1 :(得分:3)

您可以将其存储在变量中。

$result = Ping 8.8.8.8

答案 2 :(得分:1)

测试连接$ Server | Select-Object *#要获取您感兴趣的信息,然后将其包含在以下脚本中。

$server = 'Server'
test-connection $server  | format-table @{n='TimeStamp';e={Get-Date -Format yymmddhhmmss}},__SERVER, Address, ProtocolAddress, ResponseTime |`
 out-file c:\log\test-connection.txt -append

测试此脚本,然后根据需要修改输出。

答案 3 :(得分:1)

如果您只想知道是否可以ping服务器,则可以使用Test-Connection并检查其是否有值

$result = Test-Connection server.domain.tld
if( $result ){
  "Server is available"
} else {
  "Server is unreachable"
}

但是,Test-Connection已被Test-NetConnection取代,而Test-Connection的用途更为广泛。在最基本的用法下,用法类似于PingSucceeded,但即使失败的测试也会返回一个对象,因此在这种情况下,您需要检查$result = Test-NetConnection server.domain.tld if( $result.PingSucceeded ) { "Server is available" } else { "Server is unreachable" } 属性值:

Test-Connection

无论使用Test-NetConnection还是gm,都可以通过调用返回的成员并检查返回对象的方法和属性来检查每个返回的成员,如下所示(请注意{{1} }是Get-Member的别名:

Test-Connection | Get-Member
Test-NetConnection | gm

这很有用,因为您随后可以知道可以操作的属性,并知道要检查的值。

答案 4 :(得分:-4)

从互联网上找到我之后,

您只需要添加

Tee-object -FilePath C:\Users\engsooncheah\Desktop\PS\Aport2_log.txt

示例代码

$TestResults = Test-Connection -ComputerName 8.8.8.8 -Count 10| Tee-object -FilePath C:\Users\engsooncheah\Desktop\PS\Aport2_log.txt