Home > Back-end >  Configure primary DNS Setting via Powershell
Configure primary DNS Setting via Powershell

Time:12-20

I am trying to get a script to configure the primary DNS server setting.

We have mixed OSes such as 2021R2 ,2016 ,2019 and domain-joined and/or workgroup.

Mostly, We have 2 NICs on Windows Machine.

My question is: I want to change Only the primary DNS address on machine. I am trying a script like the one below. But I haven't had any luck.

script :

$wmi = Get-WMIObject Win32_NetworkAdapterConfiguration -computername localhost | where { $_.IPEnabled -eq "TRUE" -and $_.DNSServerSearchOrder -ne $null }
$dns1 = "101.61.241.311"
$wmi.SetDNSServerSearchOrder("$dns1")

script output :

__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     : 
__DYNASTY        : __PARAMETERS
__RELPATH        : 
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         : 
__NAMESPACE      : 
__PATH           : 
ReturnValue      : 70
PSComputerName   : 

Sample interface Output:

PSComputerName               : server01
DHCPLeaseExpires             : 
Index                        : 10
Description                  : vmxnet3 Ethernet Adapter
DHCPEnabled                  : False
DHCPLeaseObtained            : 
DHCPServer                   : 
DNSDomain                    : 
DNSDomainSuffixSearchOrder   : {contoso.local}
DNSEnabledForWINSResolution  : False
DNSHostName                  : server01
DNSServerSearchOrder         : {192.168.0.1, 192.168.0.2}
DomainDNSRegistrationEnabled : False
FullDNSRegistrationEnabled   : True
IPAddress                    : {192.168.0.8, fe80::cc2f:c777:11f4:4bbb}
IPConnectionMetric           : 5
IPEnabled                    : True
IPFilterSecurityEnabled      : False
WINSEnableLMHostsLookup      : True

CodePudding user response:

i would go with netsh... for example:

Netsh interface ipv4 set dns name=Ethernet static 101.61.241.311 primary

if you know the mac address or IP you can also filter for them to set the dns.

CodePudding user response:

This may be easier to do with the networking commands. Here's how to set only the primary dns server:

# Get your adapter's interface id
$interface = Get-NetIPInterface | 
  Where { $_.ConnectionState -eq 'Connected' -and $_.InterfaceAlias -notlike 'Loopback*' }

# Check the current DNS Server(s) on that interface:
$DNSCurrent = $interface | Get-DnsClientServerAddress

# fill in new dns server info:
$dns1 = '101.61.241.311'
$dns2 = $DNSCurrent.ServerAddresses[0]  # make current primary server secondary
$dns3 = $DNSCurrent.ServerAddresses[1]  # optional third


# if the first address is wrong, then set it
if ($DNSCurrent.ServerAddresses[0] -NE $dns1) {
  $interface | Set-DnsClientServerAddress -ServerAddresses $dns1,$dns2,$dns3
}
  • Related