PowerShell Script to Load Balance DNS Server Search Order

Load Balance DNS Server Search Order

DNS servers need to be configured correctly, operate perfectly and respond as fast as possible to their clients. For some applications this is critical, but many have a more relaxed attitude. Hence a DNS Server has a full second to respond to a query. That means that even when you have 2 DNS servers configured on the clients the second will only be used when the first is not available or doesn’t respond quickly enough. This has a side effect which is that moving traffic away from an overloaded DNS servers isn’t that easy or optimal. We’ll look at when to use a PowerShell script to Load balance DNS server search order.

DHCP now and then

The trick here is to balance the possible DNS servers search order amongst the clients. We used to do this via split scopes and use different DNS servers search orders in each scope. When we got Windows server 2012(R2) we not only gained policies to take care of this but also DHCP failover with replica. That’s awesome as it relieves us of much of the tedious work of keeping track of maintaining split scopes and different options on all DCHP servers involved. For more information in using the MAC addresses and DCHP policies to load balance the use of your DNS servers read this TechNet article Load balancing DNS servers using DHCP Server Policies.

Fixed IP configurations

But what about servers with fixed IP addresses? Indeed, the dream world where we’ll see dynamically assigned IP configuration everywhere is a good one but perfection is not of this world. Fixed IP configurations are still very common and often for good reasons. Some turn to DCHP reservations to achieve this but many go for static IP configuration on the servers.


When that’s the case, our sys admins are told the DNS servers to use. Most of the time they’ll enter those in the same order over and over again, whether they do this manual or automated. So that means that the first and second DNS server in the search order are the same everywhere. No load balancing to be found. So potentially one DNS server is doing all the work and getting slower at it while the second or third DNS servers in the search order only help out when the first one is down or doesn’t respond quickly enough anymore. Not good. When you consider many (most?) used AD integrated DNS for their MSFT environments that’s even less good.

PowerShell Script to Load Balance DNS Server Search Order

That’s why when replacing DNS Servers or seeing response time issues on AD/DNS servers I balance the DNS server search order list. I do this based on their IP address its last octet. If that’s even, DNS Server A is the first in the search order and if not it’s DNS Server B that goes in first. That mixes them up pseudo random enough.

I use a PowerShell script for that nowadays instead of my age-old VBScript one. But recently I wanted to update it to no longer use WMI calls to get the job done. That’s the script I’m sharing here, or at least the core cons pet part of it, you’ll need to turn it into a module and parameterize if further to suit your needs. The main idea is here offering an alternative to WMI calls. Do note you’ll need PowerShell remoting enabled and configured and have the more recent Windows OS versions (Windows Server 2012 and up).

#The transcipt provides a log to check what was found and what changed.
Start-Transcript -Path C:\SysAdmin\MyDNSUpdateLog.txt #
$VMsOnHost = (Get-VM -ComputerName MyHyperVHostorClusterName).Name

foreach ($VM in $VMsOnHost)
    Invoke-Command -ComputerName $VM -ScriptBlock {

    #This function checks if the last octet of an IP address is even or not
    Function IsLastOctetEven ($IPAddress)
             $Octets = $IPAddress.Split(".")
             #$Octets[3] #0 based array, grab 4th octet

             #See if 4th octect is even
             $Boolean = [bool]!($Octets[3]%2)
             if ($Boolean)
                 Return $Boolean
                 #write-host "even"
                 Return $Boolean
                 #write-host "odd"

        $OldDns1 = ""
        $OldDns2 = ""
        $NewDns1 = ""
        $NewDns2 = ""

        $NicInterfaces = Get-DnsClientServerAddress

        foreach ($NICinterface in $NicInterfaces)
                #Here we filter out all interfaces that are not used for client/server connectivity.
                #Cluster Interfaces, HeartBeats, Loop back adapters, ...
                #We also filter out IPv6 here as this is for a IVp4 environment.
             if($NicInterface.InterfaceAlias -notmatch "isatap" -and $NicInterface.InterfaceAlias -notmatch "Pseudo" `
                -and $NicInterface.InterfaceAlias.Contains("Local Area Connection*") -ne $True `
                -and $NicInterface.InterfaceAlias.Contains("KEMP-DSR-LOOPBACK") -ne $True `
                -and $NicInterface.InterfaceAlias.ToLower().Contains("Heartbeat".Tolower()) -ne $True `
                -and $NicInterface.InterfaceAlias.Contains("NLB-PRIVATE") -ne $True-and $NicInterface.AddressFamily -ne "23")

                $Output = "Hello from  $env:computername" + $NICinterface.InterfaceAlias
                write-Output $Output            
                $Output = $NicInterface.InterfaceAlias +": DNS1=" + $NicInterface.ServerAddresses.GetValue(0) + " & DNS2=" +  $NicInterface.ServerAddresses.GetValue(1)
                write-Output $Output

                If (($NicInterface.ServerAddresses.GetValue(0) -like $OldDns1 -or $NicInterface.ServerAddresses.getvalue(0) -like $OldDns2) -and ($NicInterface.ServerAddresses.getvalue(1) -like $oldDns1 -or $NicInterface.ServerAddresses.getvalue(1) -like $OldDns2))
                    #If the IP address is DHCP assignd, leave it alone,
                    #that's handled via DHCP policies on the MAC address
                    $GetNetIPInfo = Get-NetIpAddress -InterfaceIndex  $NicInterface.InterfaceIndex
                     if ($GetNetIPInfo.PrefixOrigin -like "DHCP")
                        write-output "DHCP address - leave it alone"
                         $IPAddresses = $GetNetIPInfo.IPv4Address
                         $FirstIP = $IPAddresses[1] #1 based array
                         if (IsLastOctetEven($FirstIP)){
                            write-output "EVEN 4th IP octet => so DNS search order becomes $NewDns1 , $NewDns2"
                            Set-DnsClientServerAddress -InterfaceIndex $NicInterface.InterfaceIndex -ServerAddresses ($NewDns1,$NewDns2)
                            write-Output "ODD 4th IP octet => so DNS search order becomes $NewDns2 , $NewDns1"
                            Set-DnsClientServerAddress -InterfaceIndex $NicInterface.InterfaceIndex -ServerAddresses ($NewDns2, $NewDns1)
                         $NicInterface |  Select-Object -ExpandProperty ServerAddresses    
                    write-Output "Existing DNS values not like expected old values. They are propably already changed"

Easily migrating non-AD integrated DNS servers while preserving server names and IP addresses


I’ll show you the quickest way to move an existing public advertising DNS deployment on Windows Server 2012R2, generation 1 virtual machines (1 primary DNS server and 1 or more secondary DNS Servers) to Windows 2016 RTM generation 2 VMs. On top of this we will preserve the sever names and the IP addresses. This makes the migration easier and it doesn’t burden anyone with updating IP addresses or FQDN of services pointing to the existing public advertising DNS service. Basically the result is the best possible for everyone involved.

Step by Step

We start by preparing a sysprepped VHDX of Windows 2016 with all the updates installed and any tools that are sysprep compatible and that you want or need on your VMs. This will allow us to make the move fast. As we want our new DNS VMs to be generation 2 VMS, make sure you use a generation 2 VM to create the syprepped OS VHDX.

The process we describe below is the same for each of the involved DNS servers. You start with the secondary VMs and end with the primary VM. This is just a form risk reduction, it’s smart to start with the secondary as it’s less critical than the primary where you make the changes.

Log on to the old, source VM and do the following

  1. Create a Folder to store the migration data and Info, i.e. C:\DNSMigrateServer01
  2. Open an elevated command prompt
  3. Run Ipconfig /all > C:\DNSMigrateServer01\Server01TCPIPinfo.txt this gives you the IP info you need for future reference.
  4. Run reg export HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\DNS\Parameters C:\DNSMigrateServer01\Dns-Service.REG
  5. Run reg export HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server” C:\DNSMigrateServer01\Dns-Software.REG
  6. In some cases, rarely for most deployments, you’ll need to also copy all files under each custom database directory on the old DNS server by manually reading from the registry at the following path: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DNS\Parameters\DatabaseDirectory If you have these also copy the directory to C:\DNSMigrateServer01. Normally when you have custom DNS database locations this is not by accident and should be well documented.
  7. Run xcopy %windir%\system32\dns C:\DNSMigrateServer01 /s This copies the content of your DNS folder (normally C:\Windows\System32\dns) to your migration folder. Note that you don’t need to copy the samples sub folder. Even the backup folder is not really needed. Just create a new backup when needed on the news DNS servers.
  8. Copy the C:\DNSMigrateServer01 from your old DNS Server to your desktop or some file share for safe keeping. You’ll need to copy this into the new DNS Server later. Note it contains your IP information, your registry exports and your DNS files.

You now have everything you need form the old DNS Server. So now we’ll decommission it, but before we do so we’ll make sure we have the options to recover it if needed.

  1. Make sure you have a backup or have made on recently (you do trust your ability to restore, right?)
  2. Shut down the VM and for good measure and fast recovery you might want to export the VM for quick import.
  3. Remove the VM from Failover Clustering if it’s clustered.
  4. Now remove the VM from Hyper-V Manager. Note this doesn’t delete the virtual disk files.
  5. Remove the old VHDX (you have an export and a backup) and replace it with your sysprepped W2K16RTM VHDX that has all the updates already. Rename that VHDX to something sensible like server01disk01.vhdx.
  6. Create a new generation 2 VM with the same name as the old one, select the required memory settings, choose to use an existing VHDX and point it to your sysprepped VHDX.
  7. Start the VM
  8. Go through the mini wizard and log in to it.
  9. Configure the NIC with the same setting as your old DNS Server
  10. Rename the VM to the old DNS VM name and join the domain.
  11. Restart the VM
  12. Login to the new DNS VM
  13. Install DNS
  14. Copy the C:\DNSMigrateServer01 you saved from your old DNS Server into the new one
  15. Open an elevated command prompt and run
    • Stop the DNS Server service by running net stop “DNS Server”
    • Double click the Dns-Service.REG and merge them into the registry


    • Double click the Dns-Software.REG files and merge them into the registry.


    • Copy all the files under C:\DNSMigrateServer01 to %windir%\System32\DNS
    • Start the DNS Server service by running net start “DNS Server”

Congratulations, you now have a new generation 2 VM running DNS on Windows Server 2016 with the same name and IP configuration as the old one. You now want to validate it’s working. To do so on the primary DNS server update the serial number in the start of authority (SOA) tab of the zone properties. I normally use YearMonthDayXX.


This will allow you to check whether the zone transfers to your migrated DNS server work. Normally all is just fine. In case things went horribly wrong you can import the VMs you exported or restore the backups. If your VMs are domain members and as you have reused the VM name, you’ll need to reestablish its domain member ship but that’s easily done.

Now repeat the above process for all the reaming secondary DNS Server and finally for the primary DNS server. Until you’ve done them all.


You do this process for every DNS Server and finally for your primary DNS server. That’s it. You’re in business and you have achieved 2 goals. You’re DNS VMs have been move to generation 2 and are running on a clean install of Windows Server 2016. All this without having to reconfigure DNS zone and transfers and while maintaining your DNS server names and IP addresses. Life is good.