Cloudflare Code to Check for Inactive DNS records

<#
  Cloudflare - List DNS records with no queries in the analytics window (no CSV export)

  Usage:
    .\InactiveDNSRercordsCloudflare.ps1 -ApiToken "<token>"
    or set $env:CLOUDFLARE_API_TOKEN and run with no arguments.

  Token needs: Zone:Read, DNS:Read, Analytics:Read
  Note: Cloudflare only retains DNS analytics for a limited period (often ~8 days
        on non-Enterprise plans), so "30 days" is best-effort.
#>
param(
    [string]$ApiToken = $env:CLOUDFLARE_API_TOKEN,
    [int]$DaysToQuery = 30,
    [int]$MaxDaysPerQuery = 6
)

if (-not $ApiToken) { Write-Error "No API token. Pass -ApiToken or set `$env:CLOUDFLARE_API_TOKEN."; exit 1 }

$Api     = "https://api.cloudflare.com/client/v4"
$Headers = @{ "Authorization" = "Bearer $ApiToken"; "Content-Type" = "application/json" }

# Verify token
try {
    $verify = Invoke-RestMethod "$Api/user/tokens/verify" -Headers $Headers
    if (-not $verify.success) { throw "Token verification failed" }
} catch {
    Write-Error "Bad token: $($_.Exception.Message)"; exit 1
}

# Fetch all pages of a paginated REST endpoint
function Get-CfPaged([string]$Url, [int]$PerPage) {
    $page = 1
    $all  = @()
    do {
        $sep  = if ($Url.Contains("?")) { "&" } else { "?" }
        $resp = Invoke-RestMethod "$Url${sep}per_page=$PerPage&page=$page" -Headers $Headers
        $all += $resp.result
        $totalPages = $resp.result_info.total_pages
        $page++
    } while ($totalPages -and $page -le $totalPages)
    return $all
}

try {
    $Zones = @(Get-CfPaged "$Api/zones" 50 | Where-Object { $_ })
} catch {
    Write-Error "Failed to list zones: $($_.Exception.Message)"; exit 1
}
if ($Zones.Count -eq 0) { Write-Error "No zones visible to this token (needs Zone:Read)."; exit 1 }
$ScriptStart = (Get-Date).ToUniversalTime()

foreach ($zone in $Zones) {
    $ZoneName = $zone.name
    Write-Host "`n=== $ZoneName ===`n" -ForegroundColor Cyan

    # 1. All DNS records
    try {
        $DnsRecords = @(Get-CfPaged "$Api/zones/$($zone.id)/dns_records" 1000 | Where-Object { $_ })
    } catch {
        Write-Warning "Failed to list DNS records for ${ZoneName}: $($_.Exception.Message)"; continue
    }

    # 2. DNS analytics (aggregated counts) in non-overlapping chunks, newest first
    $HitsByName     = @{}   # "name"      -> count
    $HitsByNameType = @{}   # "name|TYPE" -> count
    $numChunks = [Math]::Ceiling($DaysToQuery / $MaxDaysPerQuery)
    $successfulChunks = 0

    Write-Host "  Querying DNS analytics for last $DaysToQuery days ($numChunks chunks of up to $MaxDaysPerQuery days)..." -ForegroundColor Gray

    for ($chunk = 0; $chunk -lt $numChunks; $chunk++) {
        $endDt   = $ScriptStart.AddDays(-($chunk * $MaxDaysPerQuery))
        $startDt = $ScriptStart.AddDays(-[Math]::Min(($chunk + 1) * $MaxDaysPerQuery, $DaysToQuery))
        $chunkStart = $startDt.ToString("yyyy-MM-ddTHH:mm:ssZ")
        $chunkEnd   = $endDt.ToString("yyyy-MM-ddTHH:mm:ssZ")

        $queryString = @"
{
  viewer {
    zones(filter: { zoneTag: "$($zone.id)" }) {
      dnsAnalyticsAdaptiveGroups(
        filter: { datetime_geq: "$chunkStart", datetime_lt: "$chunkEnd" }
        limit: 10000
      ) {
        count
        dimensions { queryName queryType }
      }
    }
  }
}
"@
        $Body = @{ query = $queryString } | ConvertTo-Json -Depth 10

        try {
            $Analytics = Invoke-RestMethod "$Api/graphql" -Method Post -Headers $Headers -Body $Body
        } catch {
            Write-Host "  Chunk $($chunk + 1) error: $($_.Exception.Message)" -ForegroundColor Yellow
            continue
        }

        if ($Analytics.errors) {
            $errorMsg = $Analytics.errors[0].message
            if ($errorMsg -like "*older than*" -or $errorMsg -like "*retention*") {
                # Older chunks will fail too - stop going further back
                Write-Host "  Chunk $($chunk + 1) ($chunkStart to $chunkEnd): beyond analytics retention, stopping." -ForegroundColor DarkGray
                break
            }
            Write-Host "  Chunk $($chunk + 1) ($chunkStart to $chunkEnd): $errorMsg" -ForegroundColor Yellow
            continue
        }

        $groups = @($Analytics.data.viewer.zones | Select-Object -First 1 | ForEach-Object { $_.dnsAnalyticsAdaptiveGroups })
        $chunkQueries = [long]0
        foreach ($g in $groups) {
            if (-not $g -or -not $g.dimensions.queryName) { continue }
            $name = $g.dimensions.queryName.TrimEnd('.').ToLower()
            $type = "$($g.dimensions.queryType)".ToUpper()
            $cnt  = [long]$g.count

            $HitsByName[$name] = [long]$HitsByName[$name] + $cnt
            $key = "$name|$type"
            $HitsByNameType[$key] = [long]$HitsByNameType[$key] + $cnt
            $chunkQueries += $cnt
        }

        Write-Host "  Chunk $($chunk + 1) ($chunkStart to $chunkEnd): $chunkQueries queries, $($groups.Count) name/type groups" -ForegroundColor Gray
        if ($groups.Count -ge 10000) {
            Write-Warning "  Chunk $($chunk + 1) hit the 10,000 group limit - some names may be missing (reduce -MaxDaysPerQuery)"
        }
        $successfulChunks++
    }

    if ($successfulChunks -gt 0) {
        $totalQueries = ($HitsByName.Values | Measure-Object -Sum).Sum
        Write-Host "  Total: $($HitsByName.Count) unique query names, $totalQueries queries from $successfulChunks/$numChunks chunks" -ForegroundColor Gray
        if ($successfulChunks -lt $numChunks) {
            Write-Host "  Note: older data not available - results cover a shorter window than $DaysToQuery days" -ForegroundColor Yellow
        }
    } else {
        Write-Warning "Could not retrieve DNS analytics for $ZoneName - skipping (results would all show UNUSED)."
        continue
    }

    # 3. Match records to queries
    $Results = foreach ($r in $DnsRecords) {
        # Skip verification-token TXT records
        if ($r.type -eq "TXT" -and $r.content -match "google-site-verification=|facebook-domain-verification=|ms=ms\d{7,}") { continue }

        $recordName = $r.name.TrimEnd('.').ToLower()   # API returns FQDN
        $recordType = $r.type.ToUpper()

        if ($recordName.StartsWith("*.")) {
            # Wildcard: count queries for names under it that have no explicit record
            $suffix = $recordName.Substring(1)   # ".example.com"
            $explicit = @{}
            foreach ($d in $DnsRecords) { $explicit[$d.name.TrimEnd('.').ToLower()] = $true }
            $q = [long]0
            foreach ($k in $HitsByName.Keys) {
                if ($k.EndsWith($suffix) -and -not $explicit.ContainsKey($k)) {
                    if ($recordType -eq "CNAME") { $q += $HitsByName[$k] }
                    else { $q += [long]$HitsByNameType["$k|$recordType"] }
                }
            }
        } elseif ($recordType -eq "CNAME") {
            # A CNAME answers queries of any type for its name
            $q = [long]$HitsByName[$recordName]
        } else {
            $q = [long]$HitsByNameType["$recordName|$recordType"]
        }

        [pscustomobject]@{
            Name      = $r.name
            Type      = $r.type
            Content   = $r.content
            Proxied   = $r.proxied
            Queries   = $q
            Status    = if ($q -eq 0) { "UNUSED" } else { "Active" }
        }
    }
    $Results = @($Results)

    $UnusedRecords = @($Results | Where-Object { $_.Status -eq "UNUSED" } | Sort-Object Name, Type)
    $ActiveCount   = @($Results | Where-Object { $_.Status -eq "Active" }).Count

    if ($UnusedRecords.Count -gt 0) {
        Write-Host "`nUNUSED/INACTIVE DNS RECORDS ($($UnusedRecords.Count) records):`n" -ForegroundColor Red
        $UnusedRecords | Format-Table Name, Type, Content, Proxied, Queries, Status -AutoSize | Out-String -Width 4096 | Write-Host
    } else {
        Write-Host "`nNo unused/inactive DNS records found - all records are in use.`n" -ForegroundColor Green
    }

    Write-Host "Summary: $ActiveCount active records, $($UnusedRecords.Count) unused records`n" -ForegroundColor Cyan
}

Write-Host "FINISHED - checked $($Zones.Count) zone(s)." -ForegroundColor Green
(No Ratings Yet)