You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Cmd、PowerShell或C#获取Windows Server准确网络使用统计数据

解决Windows Server真实网络总流量监控问题

问题原因

你之前的方案只统计了部分网卡(比如仅物理网卡),而PerfMon/任务管理器显示的是**所有网卡(含虚拟网卡、Hyper-V虚拟交换机、VPN适配器等)**的总流量,同时需注意单位转换差异(1 Byte = 8 Bits)。

可行解决方案

1. PowerShell 实现

直接获取所有网卡的Bytes Total/sec并求和,可转换为常用的MB/s或Gbits/s单位:

# 每秒输出一次实时总流量
while($true) {
    $counterData = Get-Counter '\Network Interface(*)\Bytes Total/sec'
    $totalBytesPerSec = ($counterData.CounterSamples | Measure-Object -Property CookedValue -Sum).Sum
    $totalMBytesPerSec = [math]::Round($totalBytesPerSec / 1MB, 2)
    $totalGbitsPerSec = [math]::Round(($totalBytesPerSec * 8) / 1GB, 2)
    Write-Host "总流量: $totalMBytesPerSec MB/s | $totalGbitsPerSec Gbits/s"
    Start-Sleep -Seconds 1
}

若需排除特定网卡(比如回环适配器),可添加过滤条件:

$counterData.CounterSamples | Where-Object { $_.InstanceName -notlike "*Loopback*" } | Measure-Object -Property CookedValue -Sum

2. Cmd 实现

使用typeperf获取所有网卡数据,结合PowerShell处理求和:

# 单次获取总流量(单位:MB/s)
typeperf "\Network Interface(*)\Bytes Total/sec" -sc 1 | findstr /v "Counter" | powershell "$input | ForEach-Object { $_ -split ',' | Select-Object -Last 1 } | Measure-Object -Sum | % { [math]::Round($_.Sum/1MB,2) } MB/s"

3. C# 实现

遍历所有网络接口实例,累加Bytes Total/sec数值,注意实时采样逻辑:

using System;
using System.Diagnostics;

class NetworkTrafficMonitor
{
    static void Main()
    {
        var nicCategory = new PerformanceCounterCategory("Network Interface");
        string[] allInstances = nicCategory.GetInstanceNames();
        
        while (true)
        {
            double totalBytesPerSec = 0;
            foreach (string instance in allInstances)
            {
                if (!nicCategory.InstanceExists(instance)) continue;
                
                using (var trafficCounter = new PerformanceCounter(
                    "Network Interface", "Bytes Total/sec", instance))
                {
                    // 首次采样返回0,需等待后取有效数值
                    trafficCounter.NextValue();
                    System.Threading.Thread.Sleep(1000);
                    totalBytesPerSec += trafficCounter.NextValue();
                }
            }
            
            double totalMBytes = Math.Round(totalBytesPerSec / 1024 / 1024, 2);
            double totalGbits = Math.Round((totalBytesPerSec * 8) / 1024 / 1024 / 1024, 2);
            Console.WriteLine($"总流量: {totalMBytes} MB/s | {totalGbits} Gbits/s");
        }
    }
}

验证方式

运行上述代码后,对比任务管理器→性能选项卡中所有网络适配器的总流量,确认数值匹配(注意单位转换)。

内容的提问来源于stack exchange,提问作者andy250

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 22:03:22