Powershell script to delete a DNS record

Hi guys,

I was asked to write a script that does the following:

  1. Gets a list of DHCP Scopes
  2. Takes the hostname of all DHCP leases found in the scopes
  3. Delete each hostname from the DNS server

To get it done you will have to start by importing both DNS and DHCP PowerShell Modules:


Import-Module DNSServer
Import-Module DHCPServer

You must have them installed locally, if not you can either run the script on the server or install the DNS and DHCP RSAT.

In the next step I read a txt file which contains a list of DHCP scopes I need to read:


$ScopeList = Get-Content c:\ScopeList.txt

Now I going to run on every scope and get all the leases from that scope:


# Null value $Lease
$Leases = $Null

# Get all Leases for every scope
Foreach ($Scope in $ScopeList)
{
$Leases += Get-DhcpServerv4Lease -ComputerName dhcp01 -ScopeId $Scope | Select HostName
}

The next step is to delete each record from the DNS. Please note that ‘HostName’contains the FQDN of the computer but I need only the NETBIOS name, so I use ‘replace’ function to remove it.


Foreach ($Lease in $Leases)
{
$RecordName = $Lease.HostName -replace ".itbl0b.com",""

# Remove the DNS record
Try
{
Remove-DnsServerResourceRecord -ZoneName itbl0b.com -ComputerName dns01 -Force -RRType 'A' -Name $RecordName
Write-Verbose ("[{0}] delete record name: $RecordName" -f (Get-Date))
}
Catch
{
Write-Verbose ("[{0}] Cannot delete record name: $RecordName" -f (Get-Date))
}
}

 

That’s it!

Use this script wisely, it will delete all records from the DNS – you will have to re-register each computer.

Here’s the complete script:

DelDNSRecords

 

Incoming search terms:

  • powershell delete dns record
  • powershell to remove dns records
  • delete ns records dns powerdhell
  • remove-dnsserverresourcerecord
  • remove dns records using powershell
  • remove bad dns address via powershell
  • quest powershell script dns record
  • powershell remove dns
  • powershell dns import-module
  • powershell delete dns records by subnet

What do you think about this post?