Discovering NIC that has a specific IP Address

One question (of many) that came up at that European Deep Dive (more on that later) was finding the particular network adapter associated with an IP Address.  The problem is that IP Address (in the later versions of Windows) is a string array in WMI

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "Index=7"

returns this for the IP Address

IPAddress        : {10.10.54.202, fe80::4547:ee51:7aac:521e}

So we need a bit of magic. How can we test if an array contains a particular value?

function get-nicfromIP {            
 [CmdletBinding()]            
 param (            
  [parameter(Mandatory=$true)]            
  [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")]            
  [string]$ipaddress,            
              
  [string]$computername="$env:COMPUTERNAME"            
 )            
Write-Verbose $ipaddress            
             
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $computername |            
foreach {            
 Write-Verbose "$($_.Description)"            
 if ($($_.IPAddress) -contains $ipaddress){            
  Write-Debug "getting adapter"            
              
  Get-WmiObject -Class Win32_NetworkAdapter -Filter "DeviceID=$($_.Index)" -ComputerName $computername             
 }            
}             
}


Create a function that takes an IP Address as a parameter  (thanks to Tobias for the regex – one day I’ll learn to do them)



Use the Win32_NetworkAdapterConfiguration class to retrieve the configurations. Foreach configuration test if the IPAddress array contains the IPAddress.



The –contains operator is made for this work



If our test is true then we get the Win32_NetworkAdapter that is associated with the configuration.  I’ve just used the fact that DeviceId=Index to perform the link.



Contrary to my thinking at the Deep Dive (why didn’t we test it instead of just talking about it Sad smile) there is a WMI association between the Win32_NetworkAdapterConfiguration and the Win32_NetworkAdapter  class so we could rewrite the if statement as



function get-nicfromIP {            
 [CmdletBinding()]            
 param (            
  [parameter(Mandatory=$true)]            
  [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")]            
  [string]$ipaddress,            
              
  [string]$computername="$env:COMPUTERNAME"            
 )            
Write-Verbose $ipaddress            
             
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $computername |            
foreach {            
 Write-Verbose "$($_.Description)"            
 if ($($_.IPAddress) -contains $ipaddress){            
  Write-Debug "getting adapter"            
  $q = "ASSOCIATORS OF {Win32_NetworkAdapterConfiguration.Index=$($_.Index)}"            
  Get-WmiObject -ComputerName $computername -Query $q            
 }            
}             
}

Leave a Reply