Skip Ribbon Commands
Skip to main content

Ondrej Sevecek's English Pages

:

Engineering and troubleshooting by Directory Master!
MCM: Directory

Quick Launch

Ondrej Sevecek's English Pages > Posts > PowerShell script to automatically correct the client list of DNS servers configured on network interfaces
December 18
PowerShell script to automatically correct the client list of DNS servers configured on network interfaces

Sometimes you have a requirement to change statically configured IP addresses of DNS servers (DNS resolvers) which are configured on network interfaces (NICs) of your computers. If you configure your servers or even workstations with a static list of DNS server addresses, you would have to go to all of them manually and change the IP addresses one by one. I have just hit an environment where all machines are configured statically and what if we rather change the hundreds of configurations automatically?

I created a simple PowerShell script which detects the network adapters that need reparations and sets the correct DNS server search order

# Note: we will reconfigure all the NICs that currently
#       contain at least one of the $currentPossibleDNSs DNS server IPs 
#       among the list of its configured DNS servers. We do not touch
#       any other NICs to be on the safe side agains WiFis and VPNs
$currentPossibleDNSs = @('10.10.0.18', '10.10.0.11')

# Note: we will configure the NICs with exactly the following
#       list of DNS server IPs which gets reset to this list in effect
$newDNS = @('10.10.0.12', '10.10.0.11', '10.10.0.15')

#
#

[object[]] $nics = gwmi win32_networkadapterconfiguration | ? { $_.DNSServerSearchOrder.Count -gt 0 }

foreach ($oneNic in $nics) {

  [bool] $matches = $false

  foreach ($oneCurrentDNS in $currentPossibleDNSs) {
    
    if ($oneNic.DNSServerSearchOrder -contains $oneCurrentDNS) {

      $matches = $true
      break
    } 
  }

  if ($matches) {

    Write-Host ('One found NIC: ip = {0} | {1} | dns = {2}' -f ($oneNic.IPAddress -join ','), $oneNic.Description, ($oneNic.DNSServerSearchOrder -join ','))

    $res = $oneNic.SetDNSServerSearchOrder($newDNS)
    Write-Host ('Reconfigured: {0}' -f $res.ReturnValue)

    if ($res.ReturnValue -ne 0) {

      throw ('Cannot reconfigure search order on NIC: #{0} | error = {1}' -f $oneNic.InterfaceIndex, $res.ReturnValue)
    }
  }
}

You can either run the script from PowerShell command line manually or you can as well assing it to the computer as an Immediate Task by using the Group Policy Preferences - Scheduled Tasks feature.

Comments

There are no comments for this post.

Add Comment

Sorry comments are disable due to the constant load of spam *


This simple antispam field seems to work well. Just put here the number.

Title


You do not need to provide any value this column. It will automatically fill with the name of the article itself.

Author *


Body *


Attachments