Decluttering DNS with PowerShell
My web server hosts a number of small sites - personal, family and friends. Today, I was setting up a secondary DNS name server - something I've been meaning to do for a while - on my new storage box (which I provisioned following my recent no-backup experience!), when I noticed that several domains that I was migrating did not actually resolve to my server anymore.
I put together a short PowerShell script to pull together the domain names and IP addresses of all the domains in my DNS:
$zones = (Get-DnsServerZone | where { $_.ZoneName -notlike "*arpa*" -and $_.ZoneName -ne "TrustAnchors" })
$zones | ForEach-Object {
echo $_.ZoneName;
Try {
[System.Net.Dns]::GetHostAddresses($_.ZoneName) | foreach { echo $_.IPAddressToString }
} Catch {
echo "DNS lookup failed.";
}
}
I've never really used PowerShell before today (other than for deprovisioning Candy Crush from Windows 10 Professional), so I'm sure there is probably a more elegant way to do it!
For those who are in the same boat, the script breaks down as follows:
- Get all the zones from the DNS server, filtering out the reverse zones (e.g. 0.168.192.in-addr.arpa) and the "TrustAnchors" entry.
- For each remaining zone, output it's name. Try to look up the zone name in DNS - if successful, print out all the associated IP addresses. If not successful, just log a failure message and move on.
This left me with a list of all the DNS zones I was hosting, and the IP addresses that they currently mapped to. It turned out that four domains had been moved to other servers, so I was able to delete them.