Tag Archives: Get-Wmiobject win32_networkadapterconfiguration

Change DNS settings on multiple servers

A common change that is required to be done when doing major infrastructure upgrades is changing dns server settings on clients and servers. Something that I often see is that the changes on the servers are handled manually by logging on with RDP, changing DNS and logging of. Therefore I wanted to share a basic script that does this job for you, for all or a set of servers in Active Directory through WMI. It can of course be customized indefinitely according to your DNS topology and site structure.

By default it will target all servers that are not domain controllers, respond to ping and WMI.
If you have a simple environment with example only two or three DNS servers it’s just to change the $NewDNS array to your specific DNS servers and run the script.

ChangeDNSServers.ps1

Import-Module ActiveDirectory
#New DNS Servers in order
$NewDNS = @("10.255.255.4","10.255.255.5")
$NewDNS | ForEach-Object -Begin { Write-Output "The following DNS servers in order will be set on the machines:" ; $index = 1} -Process { Write-Output "#$($index): $_" ; $index++ }
#Get all servers in active directory (excluding domain controllers)
$ServersToChange = (Get-ADComputer -Filter {operatingsystem -like "*Server*" -and enabled -eq $true -and primarygroupid -ne '516'}).Name
#Loop through all servers and change to the new DNS servers
foreach ($Server in $ServersToChange) {
    if (Test-Connection -ComputerName $Server -Count 1 -Quiet -ErrorAction Ignore -WarningAction Ignore) {
        try {
            $wmi = Get-WmiObject -Class win32_networkadapterconfiguration -Filter "ipenabled = 'true'" -ComputerName $Server
            $wmi.SetDNSServerSearchOrder($NewDNS) | Out-Null
            Write-Output "SUCCESS: Changed DNS on $Server"
        } catch {
            Write-Warning "Error changing DNS on $Server"
        }
    } else {
        Write-Warning "Error contacting $Server`r`nDoes it respond to ping/wmi?"
    }
}

2014-11-29_12-25-52
WHAT COULD POSSIBLY GO WRONG?
Changing DNS server settings on a machine is not something that you usually think could break anything. In 11/10 times there are no issues at all. But the 12th time you do it, you might get in trouble. So, if you have Windows Server 2008/2008 R2 machines in your environment, please read KB2520155 make sure to apply proper countermeasure prior to changing DNS servers on those.

/Johan

Advertisement