1 Powershell/dns-zone-file-to-csv
Caffeine Fueled edited this page 2025-10-01 19:12:36 +00:00
# .\ZoneToCsv.ps1 -InputPath .\zones.txt -OutputPath .\zones.csv
# ZoneToCsv.ps1
param(
  [Parameter(Mandatory)] [string] $InputPath,
  [Parameter(Mandatory)] [string] $OutputPath
)

$records = New-Object System.Collections.Generic.List[object]
$currentZone = ''

Get-Content -LiteralPath $InputPath | ForEach-Object {
  $line = $_.Trim()
  if ([string]::IsNullOrWhiteSpace($line)) { return }
  if ($line.StartsWith(';') -or $line.StartsWith('#')) { return }   # comments
  if ($line.StartsWith('$')) { return }                             # directives ($ORIGIN, $TTL, etc.)

  # zone header like "example.com:"
  if ($line -match '^\s*([A-Za-z0-9\.\-\*]+):\s*$') {
    $currentZone = $matches[1].TrimEnd('.')
    return
  }

  # normalize whitespace, then parse
  $parts = -split ($line -replace '\s+', ' ')
  if ($parts.Length -lt 3) { return }

  $i = 0
  $name = $parts[$i++].TrimEnd('.')

  $ttl = ''
  if ($i -lt $parts.Length -and $parts[$i] -match '^\d+$') { $ttl = $parts[$i++]; }

  $class = ''
  if ($i -lt $parts.Length -and $parts[$i] -match '^(IN|CH|HS)$') { $class = $parts[$i++]; }

  if ($i -ge $parts.Length) { return }
  $type = $parts[$i++]

  $rdata = ($parts[$i..($parts.Length-1)] -join ' ')

  $records.Add([pscustomobject]@{
    Zone  = $currentZone
    Name  = $name
    TTL   = $ttl
    Class = $class
    Type  = $type
    RData = $rdata
  })
}

$records | Export-Csv -NoTypeInformation -Encoding UTF8 -Path $OutputPath
Write-Host "Wrote $($records.Count) records to $OutputPath"