Monday, November 28, 2011

Finding IP and MAC address

 

PowerTip of the Day, from PowerShell.com:

 

Finding IP and MAC address

When you query network adapters with WMI, it is not easy to find the active network card. To find the network card(s) that are currently connected to the network, you can filter based on NetConnectionStatus which needs to be "2" for connected cards. Then you can take the MAC information from the Win32_NetworkAdapter class and the IP address from the Win32_NetworkAdapterConfiguration class and combine both into one custom return object:

PS> Get-WmiObject Win32_NetworkAdapter -Filter 'NetConnectionStatus=2'

ServiceName : NETw5s64

MACAddress : 00:22:FA:D9:E1:50

AdapterType : Ethernet 802.3

DeviceID : 11

Name : Intel(R) WiFi Link 5100 AGN

NetworkAddresses :

Speed : 54000000

This gets you the network hardware but not the network configuration. To get the configuration data for this network card (like its IP address), get the related Win32_NetworkAdapterConfiguration instance:

########### Script Start Here ###########################

function Get-NetworkConfig {

Get-WmiObject Win32_NetworkAdapter -Filter 'NetConnectionStatus=2' |

ForEach-Object {

$result = 1 | Select-Object Name, IP, MAC

$result.Name = $_.Name

$result.MAC = $_.MacAddress

$config = $_.GetRelated('Win32_NetworkAdapterConfiguration')

$result.IP = $config | Select-Object -expand IPAddress

$result

}

}

###################### Script end Here #####################

 

PS> Get-NetworkConfig

Name IP Mac

---- -- ---

Intel(R) WiFi Link 5100... {78.64.118.150, fe80::a... 00:22:FA:D9:E1:50

 

Thanks to www.PowerShell.com

No comments:

Post a Comment