Skip to content

Instantly share code, notes, and snippets.

@davidlu1001
Last active May 6, 2024 05:20
Show Gist options
  • Select an option

  • Save davidlu1001/803695b75ff1e0dcb4b2a9bb65c9069e to your computer and use it in GitHub Desktop.

Select an option

Save davidlu1001/803695b75ff1e0dcb4b2a9bb65c9069e to your computer and use it in GitHub Desktop.
Get DNS CNAMES recursively for specified Servers
param (
[Parameter(Mandatory = $true)]
[string]$dnsServer,
[Parameter(Mandatory = $true)]
[string[]]$lookupZones,
[Parameter(Mandatory = $true)]
[string[]]$specificServerNames
)
function Get-CNameRecords {
param (
[string]$dnsServer,
[string[]]$lookupZones,
[string[]]$specificServerNames
)
$results = @()
foreach ($zone in $lookupZones) {
try {
$cnames = Get-DnsServerResourceRecord -ZoneName $zone -ComputerName $dnsServer -RRType "CNAME" -ErrorAction Stop
foreach ($cname in $cnames) {
$target = $cname.RecordData.HostNameAlias
foreach ($serverName in $specificServerNames) {
if ($target -like "*$serverName*") {
$additionalCNames = Find-CNameChain -dnsServer $dnsServer -zone $zone -target $cname.HostName
$results += [pscustomobject]@{
Zone = $zone
CName = $cname.HostName
Target = $target
AdditionalCNames = $additionalCNames -join ', '
}
}
}
}
} catch {
Write-Warning "Failed to query DNS records for zone $zone : $_"
}
}
return $results
}
function Find-CNameChain {
param (
[string]$dnsServer,
[string]$zone,
[string]$target
)
$additionalCNames = @()
try {
$cnameRecords = Get-DnsServerResourceRecord -ZoneName $zone -ComputerName $dnsServer -RRType "CNAME" -ErrorAction Stop
foreach ($record in $cnameRecords) {
if ($record.RecordData.HostNameAlias -like "*$target*") {
$additionalCNames += $record.HostName
}
}
} catch {
Write-Warning "Failed to find additional CNAME chain for $target in $zone : $_"
}
return $additionalCNames
}
# Execute the function and handle results
$results = Get-CNameRecords -dnsServer $dnsServer -lookupZones $lookupZones -specificServerNames $specificServerNames
if ($results.Count -gt 0) {
$results | Export-Csv -Path "CNameResults.csv" -NoTypeInformation
Write-Host "Results exported to CNameResults.csv"
} else {
Write-Host "No matching CNAME records found."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment