Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
DNS backup script
#Set file paths for later use
$BackupFolder = "ServerName\ShareName" # use a valid path like "\\Server01\Backups\DNSBackup"
$DNSServer = "ServerName"
$Credential = Get-PSCredential
# connect to DC as another user
$CIMSession = New-CimSession -ComputerName $DNServer -credential $Credential #Use MS Secret Mgmt to manage your credentials
#Read DNS info from DC
$ShortDate = Get-Date -Format "yyyy-MM-dd"
$LongDate = Get-Date -Format "yyyy-MM-dd_HH-mm"
$ZoneInfo = Get-DnsServerZone -CimSession $CIMSession
#Test if backup folder is already created on backup destination share
if ( -not (Test-Path "$BackupFolder\$ShortDate")) {
New-Item -Path "$BackupFolder\" -Name "$ShortDate" -ItemType "directory"
#filter out the forward & reverse zones
$ForwardZones = $ZoneInfo | Where-Object { $_.zonename -like "*.com" -and $_.zonetype -eq "Primary" } |
Select-Object -ExpandProperty ZoneName
$ReverseZones = $ZoneInfo | Where-Object ZoneName -Like "*.arpa" | Select-Object -ExpandProperty ZoneName
#Export data for each forward lookup zone
foreach ($DNSZone in $ForwardZones) {
$JobScope = "DNSBackupForwardZone"
$FileName = -join ($JobScope, "_", $($DNSZone.Replace(".", "_")), "_", $LongDate, ".dns")
try {
Export-DnsServerZone -Name $DNSZone -FileName $Filename -CimSession $CIMSession
} catch {
$_.CategoryInfo -eq 'InvalidArgument'
#Export data for each Reverse lookup zone
foreach ($DNSZone in $ReverseZones) {
$JobScope = "DNSBackupReverseZone"
$FileName = -join ($JobScope, "_", $($DNSZone.Replace(".", "_")), "_", $Longdate, ".dns")
try {
Export-DnsServerZone -Name $DNSZone -FileName $Filename -CimSession $CIMSession
} catch {
$_.CategoryInfo -eq 'InvalidArgument'
# copy files from DC to Backup folder
New-PSDrive -Name DC -PSProvider FileSystem -Root \\$DNSServer\c$\windows\system32\dns -cred $Credential
New-PSDrive -Name WebJEA -PSProvider FileSystem -Root "\\prdus2webjea01\Backups\DNSBackup\$ShortDate" -cred $Credential
$Files = Get-ChildItem DC: | Where-Object name -Like "DNSBackup*"
Copy-Item $files -Destination "$BackupFolder\$ShortDate"
# Cleanup Files, Drives and CIM Sessions
Remove-item $Files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment