powershell - 如何使用 Test-Connection 在 Powershell 中计算平均 ping 响应时间?

标签 powershell average

我是 PS 脚本的新手。我的代码需要帮助。
目的:ping .txt 文件中的 IP 列表并以 csv 格式输出结果。到目前为止,这是我的代码。

$Iplist = Get-Content ips.txt
$group = $()
foreach ($ip in $Iplist)
{
   $status = @{ "ServerIP Name" = $ip; "TimeStamp" = (Get-Date -f s) }
   if (Test-Connection $ip -Count 4 -ea 0 | measure-Object -Property ResponseTime -Average)
   {
        $status["Results"] = "Up"
   }
   else
   {
        $status["Results"] = "Down"
   }
   New-Object -TypeName PSObject -Property $status -OutVariable serverStatus
   $group += $serverStatus
}
$group | export-csv c:\ping\results.csv -NoTypeInformation

最佳答案

Test-Connection 返回 Win32_PingStatus 目的。

要在 PowerShell 类型中查看此对象上的其他可用内容:

$ping = Test-Connection www.google.com #or insert favorite url here
$ping | Format-List | Out-String
Test-Connection不只是返回一个 bool 值。你真的很接近,但你必须分配返回值才能计算成功的平均值:

$Iplist = Get-Content ips.txt
$group = @()
foreach ($ip in $Iplist) {
  $status = @{ "ServerIP Name" = $ip; "TimeStamp" = (Get-Date -f s) }
  $pings = Test-Connection $ip -Count 4 -ea 0
  if ($pings) {
    $status["AverageResponseTime"] =
        ($pings | Measure-Object -Property ResponseTime -Average).Average
    $status["Results"] = "Up"
  }
  else {
    $status["Results"] = "Down"
  }

  New-Object -TypeName PSObject -Property $status -OutVariable serverStatus
  $group += $serverStatus
}

$group | Export-Csv c:\ping\results.csv -NoTypeInformation

关于powershell - 如何使用 Test-Connection 在 Powershell 中计算平均 ping 响应时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25297977/

相关文章:

xml - 如何将 Invoke-RestMethod 的响应转换为 XML?

powershell - Visual Studio 代码 cmd 错误 : Cannot be loaded because running scripts is disabled on this system

PowerShell 为每个不同的记录创建文件

powershell - 使用PSSession时令人困惑的ErrorAction行为

mysql - 具有唯一 ID 的高级平均日期差异

cuda - 如何使用 Thrust 计算 int2 数组的平均值

powershell - Powershell-让用户从一月到十二月的列表中进行选择

MYSQL多表求和使用主键

Mysql 平均时间列?

python - 在不考虑零值的情况下使用 numpy 计算多个数组的平均值