DNS Server: Massive modification of primary zones with dnscmd

In a Windows Server 2012 R2 we would use the cmdlet Set-DNSServerPrimaryZone to change one or more primary zones with Powershell. In my case I have a Windows Server 2008 R2 so I had to use the dnscmd command to modify all the primary zones of a server and create secondary zones in another DNS server.

For instance, in DNS Server 192.168.1.25, the command to set 192.168.1.76 in the list of servers for which zone transfer is permited for zone "dominio.com" would be:
dnscmd 192.168.1.25 /zoneresetsecondaries dominio.com /securelist 192.168.1.76

Unfortunately the command will rewrite the existing server list. To avoid so, I have used besides dnscmd, a bit of powershell.


First of all we need to list all the zones of our DNS server:
dnscmd 192.168.1.25 /enumzones >DNS_listarzonas.txt
Based on previous list, I will get info of each zone:
for /f "skip=6 eol=* tokens=1,2" %%i in (DNS_listarzonas.txt) do (
 if "%%j"=="Primary" dnscmd 192.168.1.25 /zoneinfo %%i >logs\%%i.log
)
And now I will use a little of powershell to parse all logfiles of previous command, read the list of servers for which zone transfer is permited and add my new DNS Server 192.168.1.76 at the end:
$ficheros=gci ".\logs\*.log"
$currentDNSIP="192.168.1.25"
$newDNSIP="192.168.1.76"
foreach($fichero in $ficheros)
{
$currentIPs=$newIPs=$null
$content=get-content($fichero)
$zone=(($content -cmatch "Nombre de zona").split("="))[1].trim()
$transfertype=(($content -cmatch "secure secs").split("="))[1].trim()
write-host "$zone es de tipo $transfertype" -fore cyan
 if ($transfertype -eq "2")
 {
 $currentIPs=$content -cmatch 'Secundario\['
  foreach($currentIP in $currentIPs)
  {
  $IP=$currentIP.substring($currentIP.indexof("addr=")+5)
  $newIPs="$newIPS$IP "
  }
 $newIPs="$newIPS$newDNSIP"
 out-file "DNSresetsecondaries.cmd" -input "dnscmd $currentDNSIP /zoneresetsecondaries $zone /securelist $newIPs" -append -enc ascii
 }
}
This Powershell script has generated a batch file with all necessary dnscmd /resetsecondaries commands:
dnscmd 192.168.1.25 /zoneresetsecondaries dominio.com /securelist 192.168.1.26 192.168.1.76
dnscmd 192.168.1.25 /zoneresetsecondaries dominio2.com /securelist 192.168.1.27 192.168.1.76
dnscmd 192.168.1.25 /zoneresetsecondaries dominio3.com /securelist 192.168.1.26 192.168.1.27 192.168.1.76

Finally I will execute the following command to create all secondary zones in the new DNS server:
for /f "skip=6 eol=* tokens=1,2" %%i in (DNS_listarzonas.txt) do (
 if "%%j"=="Primary" dnscmd 192.168.1.76 /zoneadd %%i /secondary 192.168.1.25
)

Comments