1. The Workflow
  2. The Implementation

In dynamic DHCP environments, DNS zones become polluted with stale A-records. This script provides a surgical, auditable way to identify and purge stale DNS records older than a defined threshold.

1. The Workflow

The script performs the following steps:

  • Targeting: Selects a specific internal DNS zone.
  • Evaluation: Pulls all A records and compares the Timestamp against a 14-day threshold.
  • Execution: Exports a CSV log of the stale records before actively removing them from the server.

2. The Implementation

$ZoneName = "internal.avanster.tech"
$ThresholdDate = (Get-Date).AddDays(-14)

$Records = Get-DnsServerResourceRecord -ZoneName $ZoneName -RRType "A"
foreach ($Record in $Records) {
    if ($Record.Timestamp -ne $null -and $Record.Timestamp -lt $ThresholdDate) {
        Remove-DnsServerResourceRecord -ZoneName $ZoneName -InputObject $Record -Force
        Write-Host "[-] Removed: $($Record.HostName)"
    }
}