Automated change of DNS hosts on multiple servers in AD Organizational Unit

Change of DNS settings on remote hosts can be done either with DHCP scope settings (if your servers are using DHCP and in most cases they are not) or via Group Policy or… with Powershell. But hey, I’m pretty sure you did not enable PSRemoting on all of your servers, did ya? Luckily there’s a WMI and we can combine it with powershell.

First of all, we need to locate our target servers and here, you should be aware of one thing – each server version had different default network name. As for Windows 2012 it’s “Ethernet”, for Windows 2008 it was “Local Area Connection”. And this actually matters if you never had your own naming standard (…Today I learned it’s good to have one), because we need to specify exact name of a network we want to change these DNS settings on. Okay, let’s locate our servers using Get-ADComputer cmdlet:

I do specify *Windows Server 2012* here, because as mentioned above I want to target one of default network names (in this case it would be “Ethernet”). Of course this can be changed to *Windows Server 2008*, but then you’d have to change target network name to “Local Area Connection”. To locate network adapters we gonna use following WMI query:

$Servername variable will be pipelined from our Get-ADComputer cmdlet, NetConnectionStatus contains integer value of 2 which means connection is up & running, you can change that to “7” which indicates disconnected adapters. Normally this query should return following variables:

win32_networkadapter
win32_networkadapter

What’s important for us in output shown above is DeviceID / Index which will be used as script’s target. Another thing we want to use is WMI’s “SetDNSServerSearchOrder” method which uses an array of string elements to set the server search order.

Okay, let’s connect all these things together to make things run in the backgroud of coffee break:

First 3 lines of script are highlighted as you may (should) change them to your own values. Keep in mind all server version differences I mentioned in the beginning of this post.

Proper output of this script will look like:

change_of_dns_servers

As you can see, i tried to exclude some of frequent errors:

%ServerName% is not configured with %Network Name% or specified network is not in use (disabled) – means there is nothing like $networkname you configured in 3rd line of the script or this network is in NetConnectionStatus other than “2” (online).

%ServerName% is not reachable – means we tried to ping this server in 6th line of script, but result was “False”. You can try it again by using following (6th) line of script: “Test-Connection -Cn $ServerName -BufferSize 16 -Count 1 -ea 0 -quiet” – simply replace $servername variable with server returned in the script ‘s output.

I hope you will find this post & script useful. If so, please don’t hesitate to leave a comment / feedback below as it’s always appreciated!

Leave a Reply