1.通過性能計數器取網卡流量
$public_interface = "Broadcom BCM5709C NetXtreme II GigE [NDIS VBD 用戶端]"
$counter = New-Object Diagnostics.PerformanceCounter
$counter.CategoryName = "Network Interface"
$counter.InstanceName = $public_interface
#$counter.CategoryName = "Processor Information(_Total)"
#添加計數器屬性值,此處監視可用記憶體
$counter.CounterName = "Bytes Sent/sec"
#$counter.CounterName = "Bytes Received/sec"
#$counter.nextsample() #取樣本(RawValue),需要間隔1秒,取兩個sample做減法,才能得出每秒流量
#擷取目前計數器的值
$value = $counter.NextValue()
Start-Sleep -Seconds 1
$counter.NextValue()
2.通過get-counter取網卡流量(PS2.0)
#$networkcounter = get-counter -counter "\Network Interface(Broadcom BCM5709C NetXtreme II GigE [NDIS VBD 用戶端])\Bytes Sent/sec" #-continuous
$networkcounter = get-counter -counter "\Network Interface($public_interface)\Bytes Sent/sec" #-continuous
($networkcounter.CounterSamples|Select CookedValue).CookedValue
#檢查機器上配置IP的網卡數量,配置了gateway的網卡為Public,否則為Private
[array]$netifs = gwmi Win32_NetworkAdapterConfiguration -Filter "IPEnabled='true'"
If ($netifs.count -eq 1)
{$public_interface = $netifs[0].Description.replace("(","[").replace(")","]").replace("#","_")}
If ($netifs.count -eq 2)
{
$public_interface = ($netifs | ? {$_.DefaultIPGateway -ne $null}).Description.replace("(","[").replace(")","]").replace("#","_")
$private_interface = ($netifs | ? {$_.DefaultIPGateway -eq $null}).Description.replace("(","[").replace(")","]").replace("#","_")
}
#定義函數,通過性能計數器取網卡發送/接收流量
Function Netif_Sent_Received($interfacename,$send_member,$receiev_member)
{
$counter_Sent = New-Object Diagnostics.PerformanceCounter
$counter_Receive = New-Object Diagnostics.PerformanceCounter
$counter_Sent.CategoryName = "Network Interface"
$counter_Receive.CategoryName = "Network Interface"
$counter_Sent.InstanceName = $interfacename
$counter_Receive.InstanceName = $interfacename
$counter_Sent.CounterName = "Bytes Sent/sec"
$counter_Receive.CounterName = "Bytes Received/sec"
$value_Sent = $counter_Sent.NextValue()
$value_Receive = $counter_Receive.NextValue()
Start-Sleep -Seconds 1
$Sent = $counter_Sent.NextValue()
$Receive = $counter_Receive.NextValue()
$i_object | Add-Member -MemberType NoteProperty -name $send_member -value $sent
$i_object | Add-Member -MemberType NoteProperty -name $receiev_member -value $receive
}
#将所有結果存放到$i_object對象中
$i_object = New-Object system.object
If ($private_interface -ne $null)
{Netif_Sent_Received $private_interface Private_Send Private_Receive}
If ($public_interface -ne $null)
{Netif_Sent_Received $public_interface Public_Send Public_Receive}