次の方法で共有


WMI events

Smarter than polling

Suppose you want to know if a network adapter is connected.  If you read our last WMI blog post, you're already clever enough to solve this handily: just query MSNdis_LinkState and execute  the WmiQueryLinkState method.  This is great if you need to poll the NIC for connectivity status — but what if you want to make better use of system resources by avoiding polling?  Is it possible for event-driven code to be notified when the link state changes?

PowerShell 2.0 has great integration with WMI Events, letting you invoke a PowerShell script whenever an event is emitted.  Even better, NDIS has built-in support for a couple dozen events that you can register for.  These events are available on Windows XP and later (although PowerShell 2.0 needs to be installed separately).  Here's a simple example:

PS > $Event = Register-WMIEvent -Namespace root\wmi -Class MSNdis_StatusMediaConnect -Action {
Write-Host $(Get-Date), $Event.SourceEventArgs.NewEvent.InstanceName
}

This command creates a PowerShell event, and wires it up to a WMI event.  This event is triggered whenever an adapter sends up a Connected status indication (either NDIS_STATUS_MEDIA_CONNECT or NDIS_STATUS_LINK_STATE containing MediaConnectStateConnected).  When the PowerShell event executes, it prints a timestamp and the adapter's Instance Name (aka, ifDescr) to the console.

Now you have everything you need to write a script to send an alert email whenever the network cable gets unplugged*.

* Except for the trifling detail that email doesn't work so well while the network is unplugged.

Comments

  • Anonymous
    March 09, 2012
    Its been a long time since we have heard from you ndisstream! As a NDIS driver writer, I sure would love some more updates on NDIS6.3, power shell, and other NDIS topics.