PowerShell: Check IP Conflicts of Computers in Active Directory

We have ran into issues where a group of virtual machines living on a DHCP subnet get rebooted due unexpected events. Upon restarting, those machines would receive IP assignments from the DHCP server. In an ideal environment where Admins follow the strict procedure of creating IP reservations for each VM, using its MAC Address, everything would work fine. However, in the real world, human errors caused by skipping the IP Reservation steps would lead to instances where a DHCP server would assign duplicated IP addresses to certain machines. This is even more evidenced when IPs have already been set as static on machines that are in scope of DHCP. In such scenarios, IP conflicts would ensue. As many Windows machines are Active Directory & DNS integrated, erroneous a-records and reverse lookup results would also be incorrect. Here’s a quick script to detect those anomalies on a short list of known machine. Future versions would enable the program to scan a whole subnet to gather these machine names automatically. Until then…

$computernames=@(
    'server001',
    'server002',
    'server003'
)

function checkIpConflicts($computerNames){
  $results=@()
  foreach ($computer in $computernames){
    $ipAddress=[System.Net.Dns]::GetHostAddresses($computer)
    $ipReverseLookup=[System.Net.Dns]::GetHostEntry($ipAddress).HostName
    $isMismatched=$computer.split('.')[0] -ne $ipReverseLookup.split('.')[0]
    $dnsRecordMac=if($isMismatched){
      try{
        (Get-CimInstance -ClassName Win32_NetworkAdapterConfiguration -Filter "IPEnabled='True'" -ComputerName $ipReverseLookup -EA Stop).MacAddress
      }catch{
        write-warning $_
        'ConnectionError'
      }
      }else{'N/A'}
    $results+=[pscustomobject]@{
      computerName=$computer
      ipAddress=$ipAddress
      ipReverseLookup=$ipReverseLookup
      macAddress=(Get-CimInstance -ClassName Win32_NetworkAdapterConfiguration -Filter "IPEnabled='True'" -ComputerName $computer).MacAddress
      isMismatched=$isMismatched
      dnsRecordMac=$dnsRecordMac
    }
  }
  return $results
}

checkIpConflicts $computerNames
Sample Output:

computerName    ipAddress       ipReverseLookup                macAddress                             isMismatched dnsRecordMac
------------    ---------       ---------------                ----------                             ------------ ------------
server00001   {x.x.x.x}  server00008        00:15:5D:xx:xx:xx                              True ConnectionError
server00002      {x.x.x.x} server00002.kimconnect.com      00:0C:29:xx:xx:xx                             False N/A

Leave a Reply

Your email address will not be published. Required fields are marked *