Last active
November 29, 2023 04:55
-
-
Save compwiz32/242a011482a314085c0a2fcec370829f to your computer and use it in GitHub Desktop.
DNS backup script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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