Saturday, January 28, 2012

PowerShell: Delete Child Domain DNS Records Using DNSCMD

One of the departments on campus recently upgraded their systems (located in child domain) and requested that my unit clean up their old DNS records and the IPv6 records for systems they forgot to disable IPv6 on. So I sent them an Excel spreadsheet of their records and then sent me back which ones to delete. Then I created the script below to remove the 400+ records. Due to the way the DNSCMD command works, I had to add some serious variable checking and a five second delay between records so that it would work.

##############################################################################

# Script Name: DNS_Delete_Records_Listed_in_CSV.ps1

# Version: 1.0

# Author: Dean Bunn

# Last Edited: 01/27/2012

# Description: Deletes Child Domain DNS Entries from CSV File

##############################################################################

#Var for DNS Server

$dnsServer = "dc1.mycollege.edu"

#Var for DNS Zone

$dnsZone = "mycollege.edu"

#Var for Child Domain Name

$childDomain = "adax"

#Load CSV of Records to Be Deleted (Headers: Name, Type, and Data)

$dnsDeleteRecords = Import-Csv "c:\Users\adminaccount\Desktop\DNS_Delete.csv"

foreach($ddr in $dnsDeleteRecords)

{

#Var for Host Name

$hostName = $null

#Var for Record Type

$rType = $null

#Var for IP Address

$ipAddr = $null

#Check Length of Host Name Before Assigning Var

if($ddr.Name.ToString().Trim().Length -gt 1)

{

#Compose Hostname As SystemName.ChildDomain

$hostName = $ddr.Name.ToString().Trim() + "." + $childDomain.ToString()

}

#Switch Statement for Record Type

switch($ddr.Type.ToString().Trim())

{

"Host (A)"

{

$rType = "A"

}

"IPv6 Host (AAAA)"

{

$rType = "AAAA"

}

#Add Additional Record Types When Necessary

}

#Check the Length of the IP Address Information

if($ddr.Data.ToString().Trim().Length -gt 8)

{

#Assign IP Addr Var

$ipAddr = $ddr.Data.ToString().Trim()

}

if($rType -ne $null -and $hostName -ne $null -and $ipAddr -ne $null)

{

#Compose DNSCMD with Variables

#Should Look Like "dnscmd dc1.mycollege.edu /RecordDelete mycollege.edu dept-webstudent.adax A 192.168.60.49 `/f"

[string]$dnsDltCmd = "dnscmd $dnsServer /RecordDelete $dnsZone $hostName $rType $ipAddr `/f"

#Run the DNSCMD and Wait Five Seconds Before Moving to Next Entry

Invoke-Expression $dnsDltCmd

Start-Sleep -Seconds 5

}

else

{

Write-Host "Not Enough Info for " $ddr.Name

}

}#End of Foreach on $dnsDeleteRecords



No comments: