Discovering Network Access

by Feb 6, 2013

PowerShell can access low-level COM interfaces to find out system information such as network access. This code returns a list of all active network adapters and works with Vista/Server 2008 and above:

$cat = 'Public', 'Private', 'Domain'
$GUID = [guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}'
$network = [Activator]::CreateInstance([type]::GetTypeFromCLSID($GUID))
$network.GetNetworkConnections() | 
  ForEach-Object { 
    $result = $_ | Select-Object -Property Name, Description, *, Category
    $result.Name = $_.GetNetwork().GetName()
    $result.Description = $_.GetNetwork().GetDescription()
    $result.Category = $cat[$_.GetNetwork().GetCategory()]
    $result
} 

If you wonder why the list of properties submitted to Select-Object consists of named properties as well as "*", here's the scoop: the "*" selects all existing properties, and in addition to these, Select-Object also adds three new properties that get filled with custom values afterwards. This way, you can easily append object properties.

The result may look similar to this:

Name                  : internet-cafe  3
Description           : internet-cafe
IsConnectedToInternet : True
IsConnected           : True
Category              : Private

Name                  : Unidentified network
Description           : Unidentified network
IsConnectedToInternet : False
IsConnected           : False
Category              : Public

As you see, the properties Name, Description, and Category are the new properties added in the ForEach-Object loop. IsConnectedToInternet and IsConnected are the native properties that were present by default in the objects received by GetNetworkConnections().

Twitter This Tip! ReTweet this Tip!