gpt4 book ai didi

Powershell - 发送/接收的字节数

转载 作者:行者123 更新时间:2023-12-02 23:11:23 29 4
gpt4 key购买 nike

我需要创建一个脚本,每 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

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

最佳答案

虽然我无法解释您的方法之间的差异,但我可以为您提供一个替代方案,该替代方案应该适用于 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 没有区分?只是猜测,但这可能解释了增加的字节数。遗憾的是,文档中没有详细信息

关于Powershell - 发送/接收的字节数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39284685/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com