Powershell - 发送/接收的字节数

时间:2016-09-02 05:10:46

标签: powershell

我需要创建一个脚本,每隔30秒对网络流量进行一次采样,并存储发送/接收的字节数。然后将该数据用于绘制图形。我写了一个在Windows 2012上完美运行但我意识到某些cmdlet在2008之前的版本中不可用,因此我正在寻找替代方案。

对于Windows 2012,我使用get-netadapterstatistics来获取接收/发送的字节但是这在2012年之前无法工作所以我认为我可以使用netstat -e但问题是两者都给了我完全不同的结果我是希望有人能告诉我为什么?编写下面的脚本是为了查看数据之间的差异。

function getNic{
$nic = Get-NetRoute | ? DestinationPrefix -eq '0.0.0.0/0' | Get-NetIPInterface | Where ConnectionState -eq "Connected" | Select -ExpandProperty InterfaceAlias
return $nic
}

function getBR{
   $b = ((netstat -e | Select-String "Bytes") -split '\s+')[2]
   $a = (Get-NetAdapterStatistics |Where InterfaceAlias -eq $nic_name   |Select -ExpandProperty SentBytes)

   $a - $script:startbr
   $b - $script:startbr2
   $script:startbr = $a
   $script:Startbr2 = $b

}


$nic_name = getNic
$startbr = (Get-NetAdapterStatistics |Where InterfaceAlias -eq    $nic_name |Select -ExpandProperty SentBytes)
 $startbr2 = ((netstat -e | Select-String "Bytes") -split '\s+')[2]

for(1..1000){
    getBR

    Start-Sleep 5
}

结果如下

0
0
4577
18308
6695
26780
9055
36220

理想情况下,我只对捕获外部接口上的流量感兴趣。

1 个答案:

答案 0 :(得分:4)

虽然我无法向您解释您的方法之间的差异,但我可以为您提供一个适用于2012年之前以及2012年之前的替代方案:

$ifIndex = Get-WmiObject -Class win32_ip4routetable | where {$_.destination -eq "0.0.0.0"} | select -ExpandProperty InterfaceIndex
$ifIndex = "InterfaceIndex=" + $ifIndex
$nic_name = Get-WmiObject -Class win32_networkadapterconfiguration -Filter $ifIndex | select -ExpandProperty Description
$nic = [System.Net.NetworkInformation.Networkinterface]::GetAllNetworkInterfaces() | where {($_.description -eq $nic_name) -and ($_.operationalstatus -eq "up")}
$stats = $nic.GetIPv4Statistics()
$bytesSent = $stats.BytesSent
$bytesReceived = $stats.BytesReceived

这使得结果与我系统上的Get-NetAdapterStatistics Cmdlet一致

在考虑之后,可能netstat显示多个网络适配器(可能包括环回)的统计数据,因为没有区分nic?只是猜测,但这可能解释了增加的字节数。遗憾的是,文档中没有详细信息

相关问题