通过Powershell配置主DNS设置



我正在尝试获得一个脚本来配置主DNS服务器设置。

我们有混合操作系统,如2021R2,2016,2019和域加入和/或工作组。

大多数情况下,我们在Windows机器上有2个网卡。

我的问题是:我只想更改机器上的主DNS地址。我正在尝试像下面的一个脚本。但是我没有任何运气。

脚本:

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

脚本输出

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

接口输出:

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

我会选择netsh…例如:

Netsh interface ipv4 set dns name=Ethernet static 101.61.241.311 primary

如果你知道mac地址或IP,你也可以为他们过滤设置dns。

使用网络命令可能更容易完成。以下是如何只设置主dns服务器:

# 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
}

最新更新