Thursday, December 29, 2016

Nslookup with PowerShell

I needed a method of validating that  our PTR records matched our DNS records.  I found a lot of scripts that did pieces of each.  I created a script that uses the nslookup tool in Windows and parses the results.  This version does one host at a time but I'm working on integrating it into my DNS validator script.  This is a quick and dirty script, feel free to use it as you see fit.

#Requires -version 3.0
Clear-Host

$Target = "hostname"
Write-Host "Target Hostname = $Target" -ForegroundColor Yellow

$HostLookup = (nslookup $Target )
$Lookup = [PSCustomObject]@{
    DNS_Host = ($HostLookup[0] -split ‘:’)[1].Trim()
      DNS_IP = ($HostLookup[1] -split ‘:’)[1].Trim()
 Target_Host = ($HostLookup[3] -split ‘:’)[1].Trim()
   Target_IP = ($HostLookup[4] -split ‘:’)[1].Trim()
}

Write-Host "Target IP from NSLOOKUP ="$Lookup.Target_IP -ForegroundColor Cyan

$IPLookup = (nslookup $Lookup.Target_IP )
$RevLookup = [PSCustomObject]@{
    DNS_Host = ($IPLookup[0] -split ‘:’)[1].Trim()
      DNS_IP = ($IPLookup[1] -split ‘:’)[1].Trim()
 Target_Host = ($IPLookup[3] -split ‘:’)[1].Trim()
   Target_IP = ($IPLookup[4] -split ‘:’)[1].Trim()
}

If ($Lookup.DNS_Host -ne $RevLookup.DNS_Host){Write-Host DNS Host Mismatch -ForegroundColor Red}
ElseIf($Lookup.DNS_IP -ne $RevLookup.DNS_IP){Write-Host DNS IP Mismatch -ForegroundColor Red}
ElseIf ($Lookup.Target_Host -ne $RevLookup.Target_Host){Write-Host IP Mismatch -ForegroundColor Red}
ElseIf ($Lookup.Target_IP -ne $RevLookup.Target_IP){Write-Host IP Mismatch -ForegroundColor Red}
Else {Write-Host No Mismatch Found -ForegroundColor Green}

$Lookup.PsObject.Members|%{$Lookup.PsObject.Members.Remove($_.Name)}

$RevLookup.PsObject.Members|%{$RevLookup.PsObject.Members.Remove($_.Name)}