WMI/netsh to add DNS servers on network adapters

Reading Time: 2 Minutes

How to add DNS servers – or resolvers – to a network adapter or interface with WMI and the netsh command. This one is quite old but may come in handy sometimes. In this example we use Google’s Public DNS server addresses and localhost to add as DNS Servers on our server.

WMI and netsh to add DNS servers on network adapters for IPv4 and IPv6 addresses #

The WMI class only can add IPv4 addresses on interfaces. Therefor we use netsh for IPv6. The class Win32_NetworkAdapter is used to lookup the interface name and that interface is configured with the Win32_NetworkAdapterConfiguration WMI class.

Advertisement:

AddDnsServers.ps1:

[array]$nics = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled=true"
$dnsservers = "127.0.0.1", "8.8.8.8", "8.8.4.4"
$nics[0].SetDNSServerSearchOrder($dnsservers)
$index = $nics[0].index
$adapter = (Get-WmiObject -Class Win32_NetworkAdapter -Filter "DeviceID=$index").NetConnectionID

netsh interface ipv6 set dns "$adapter" static "2001:4860:4860::8888" primary
netsh interface ipv6 add dns "$adapter" "2001:4860:4860::8844" index=2

If you want to add more than two name servers, increase the index number:

netsh interface ipv6 set dns "$adapter" static "::1" primary
netsh interface ipv6 add dns "$adapter" "2001:4860:4860::8888" index=2
netsh interface ipv6 add dns "$adapter" "2001:4860:4860::8844" index=3

Note: The Win32_NetworkAdapter class is deprecated. Use the MSFT_NetAdapter class instead.


Did you like this post? Or did it help you solve a problem?

Advertisement:

Hi! Join the discussion, leave a reply!