使用 PowerShell 在 Windows 上配置網絡設置:IP 地址、DNS、默認網關、靜態路由

Jacki

在 Windows 中,您不僅可以從 GUI 管理網絡適配器的設置,還可以從 PowerShell 命令提示符管理網絡適配器的設置。在本文中,我們將介紹最重要的 cmdlet,您可以使用它們來查找網絡適配器的當前 IP 地址、分配靜態 IP 地址、分配 DNS 服務器 IP 或配置網絡接口以從 DHCP 服務器接收 IP 配置。您可以使用這些 cmdlet 在 Windows 10/11 和 Windows Server(或 Server Core 版本)、Hyper-V Server 上配置網絡,以更改遠程計算機上以及 PowerShell 自動化腳本中網絡適配器的 IP 設置。

內容:

此前,netsh interface ipv4 命令用於從 CLI 管理網絡設置。在 PowerShell 3.0 及更高版本中,您可以使用內置網絡TCPIP用於管理 Windows 上的網絡設置的 PowerShell 模塊。

要獲取此模塊中的 cmdlet 列表,請運行以下命令:

get-command -module NetTCPIP

該模塊還包括 Test-NetConnection cmdlet,可用於查找遠程計算機上打開的 TCP 端口。

列出 Windows 計算機上的可用網絡接口:

Get-NetAdapter

該 cmdlet 返回接口名稱、其狀態(Up/Down)、MAC 地址和端口速度。

在此示例中,我的計算機上有多個網絡適配器(除了物理連接、Ethernet0 之外,我還有 Hyper-V 和 VMWare Player 網絡接口)。

僅顯示已啟用的物理網絡接口:

Get-NetAdapter -Physical | ? {$_.Status -eq "Up"}

您只能查看某些網絡適配器參數,例如名稱、速度、狀態或 MAC 地址:

Get-NetAdapter |Select-Object name,LinkSpeed,InterfaceOperationalStatus,MacAddress

Windows 可能有一些隱藏的網絡適配器。要顯示全部內容,請添加包括隱藏範圍:

Get-NetAdapter –IncludeHidden

結果將是用於不同類型連接(包括 VPN)的所有虛擬 WAN 微型端口適配器的列表。重新啟動這些適配器通常可以修復內置 Windows 客戶端的一些 VPN 連接錯誤。有單獨的 PowerShell cmdlet 用於管理 VPN 連接。

您可以通過網絡接口的名稱或索引(索引列)來引用網絡接口。在我們的示例中,要選擇物理 LAN 適配器 Intel 82574L 千兆位網絡連接,請使用以下命令:

Get-NetAdapter -Name Ethernet0

或者:

Get-NetAdapter -InterfaceIndex 8

您可以更改適配器名稱:

Rename-NetAdapter -Name Ethernet0 -NewName LAN

要禁用網絡接口,請使用以下命令:

Get-NetAdapter -Name Ethernet0| Disable-NetAdapter

按名稱啟用 NIC:

Enable-NetAdapter -Name Ethernet0

如果網卡已配置VLAN號,可以查看:

Get-NetAdapter | ft Name, Status, Linkspeed, VlanID

您可以通過以下方法找到有關您正在使用的網絡適配器驅動程序的信息:

Get-NetAdapter | ft Name, DriverName, DriverVersion, DriverInformation, DriverFileName

列出物理網絡適配器的信息(PCI插槽、總線等):

Get-NetAdapterHardwareInfo

禁用網絡接口的 IPv6 協議:

Get-NetAdapterBinding -InterfaceAlias Ethernet0 | Set-NetAdapterBinding -Enabled:$false -ComponentID ms_tcpip6

禁用網絡接口的 NetBIOS 協議:

Set-NetAdapterBinding -Name Ethernet0 -ComponentID ms_netbios -AllBindings -Enabled $True

如何使用 PowerShell 獲取 IP 地址設置

要獲取 Windows 中當前的網絡適配器設置(IP 地址、DNS、默認網關):

Get-NetIPConfiguration -InterfaceAlias Ethernet0

有關的:配置 DNS 清理以清理 AD 中過時的 DNS 記錄

要顯示有關網絡接口 TCP/IP 配置的更多詳細信息,請使用以下命令

Get-NetIPConfiguration -InterfaceAlias Ethernet0 -Detailed

在這種情況下,會顯示接口分配的網絡位置(配置文件)(NetProfile.NetworkCategory)、MTU 設置 (NetIPv4Interface.NlMTU)、是否啟用從 ​​DHCP 獲取 IP 地址 (NetIPv4Interface.DHCP) 以及其他有用信息。

僅獲取 IPv4 接口地址:

(Get-NetAdapter -Name ethernet0 | Get-NetIPAddress).IPv4Address

僅返回接口 IP 地址的值:

(Get-NetAdapter -Name ethernet0 | Get-NetIPAddress).IPv4Address

將文件複製到虛擬機時,許多管理員注意到啟用了 Hyper-V 角色的 Windows Server 2019 上的網絡性能較差。在這種情況下,將 TCP 堆棧設置恢復為 Windows Server 2016 中使用的設置將有助於解決問題:
Set-NetTCPSetting -SettingName DatacenterCustom,Datacenter -CongestionProvider DCTCP
Set-NetTCPSetting -SettingName DatacenterCustom,Datacenter -CwndRestart True
Set-NetTCPSetting -SettingName DatacenterCustom,Datacenter -ForceWS Disabled

顯示可以為網絡適配器啟用或禁用的網絡協議的列表:

Get-NetAdapterBinding -Name ethernet0 -IncludeHidden -AllBindings

Name                           DisplayName                                        ComponentID          Enabled
----                           -----------                                        -----------          -------
Ethernet                       File and Printer Sharing for Microsoft Networks    ms_server            True
Ethernet                       NetBIOS Interface                                  ms_netbios           True
Ethernet                       Microsoft LLDP Protocol Driver                     ms_lldp              True
Ethernet                       Microsoft NDIS Capture                             ms_ndiscap           True
Ethernet                       Internet Protocol Version 4 (TCP/IPv4)             ms_tcpip             True
Ethernet                       Microsoft RDMA - NDK                               ms_rdma_ndk          True
Ethernet                       Microsoft Network Adapter Multiplexor Protocol     ms_implat            False
Ethernet                       Link-Layer Topology Discovery Mapper I/O Driver    ms_lltdio            True
Ethernet                       NDIS Usermode I/O Protocol                         ms_ndisuio           True
Ethernet                       Point to Point Protocol Over Ethernet              ms_pppoe             True
Ethernet                       Link-Layer Topology Discovery Responder            ms_rspndr            True
Ethernet                       Internet Protocol Version 6 (TCP/IPv6)             ms_tcpip6            True
Ethernet                       Hyper-V Extensible Virtual Switch                  vms_pp               False
Ethernet                       WFP Native MAC Layer LightWeight Filter            ms_wfplwf_lower      True
Ethernet                       Client for Microsoft Networks                      ms_msclient          True
Ethernet                       Npcap Packet Driver (NPCAP)                        INSECURE_NPCAP       True
Ethernet                       WINS Client(TCP/IP) Protocol                       ms_netbt             True
Ethernet                       Bridge Driver                                      ms_l2bridge          True
Ethernet                       WFP 802.3 MAC Layer LightWeight Filter             ms_wfplwf_upper      True
Ethernet                       QoS Packet Scheduler                               ms_pacer             True

要查看計算機上的活動 TCP/IP 會話,請使用 Get-NetTCPConnection cmdlet。

使用 PowerShell 在 Windows 上設置靜態 IP 地址

讓我們嘗試為 NIC 設置靜態 IP 地址。要更改 Ethernet0 網絡接口的 IP 地址、網絡掩碼和默認網關,請使用以下命令:

Get-NetAdapter -Name Ethernet0| New-NetIPAddress –IPAddress 192.168.2.50 -DefaultGateway 192.168.2.1 -PrefixLength 24

您可以使用數組結構設置 IP 地址(更直觀):

$ipParams = @{
InterfaceIndex = 8
IPAddress = "192.168.2.50"
PrefixLength = 24
AddressFamily = "IPv4"
}
New-NetIPAddress @ipParams

您可以使用 New-NetIPAddress 將第二個 IP 地址(別名)添加到網絡適配器。

如果已配置靜態 IP 地址並需要更改,請使用設置 NetIP 地址小命令:

Set-NetIPAddress -InterfaceAlias Ethernet0 -IPAddress 192.168.2.90

要禁用從 DHCP 為您的適配器獲取 IP 地址,請運行以下命令:

Set-NetIPInterface -InterfaceAlias Ethernet0 -Dhcp Disabled

刪除靜態IP地址:

Remove-NetIPAddress -IPAddress "xxx.xxx.xxx.xxx"

使用 PowerShell 在 Windows 中設置 DNS 服務器 IP 地址

要在 Windows 中設置首选和備用 DNS 服務器 IP 地址,請使用設置 DNSClientServerAddresscmdlet。例如:

Set-DNSClientServerAddress –InterfaceIndex 8 –ServerAddresses 192.168.2.11,10.1.2.11

您還可以使用數組指定 DNS 名稱服務器 IP:

$dnsParams = @{
InterfaceIndex = 8
ServerAddresses = ("8.8.8.8","8.8.4.4")
}
Set-DnsClientServerAddress @dnsParams

更改 DNS 設置後,您可以刷新 DNS 解析器緩存(相當於ipconfig /flushdns):

Clear-DnsClientCache

在 Windows 中顯示 DNS 緩存內容::
Get-DnsClientCache

使用 PowerShell 管理路由表

獲取 NetRoutecmdlet 用於顯示路由表。

獲取 Windows 中物理網絡接口的默認網關路由:

Get-NetAdapter -Physical | ? {$_.Status -eq "Up"}| Get-netroute| where DestinationPrefix -eq "0.0.0.0/0"

要添加新路線,請使用新網絡路由小命令:

New-NetRoute -DestinationPrefix "0.0.0.0/0" -NextHop "192.168.2.2" -InterfaceIndex 8

該命令將一條永久路由添加到路由表中(類似於route -p add)。如果要添加臨時路由,請添加-PolicyStore "ActiveStore"選項。重新啟動 Windows 後該路由將被刪除。

從路由表中刪除一條路由:

Remove-NetRoute -NextHop 192.168.0.1 -Confirm:$False

PowerShell:將適配器從靜態 IP 地址更改為 DHCP

要將計算機配置為從 DHCP 服務器獲取網絡適配器的動態 IP 地址,請運行以下命令:

Set-NetIPInterface -InterfaceAlias Ethernet0 -Dhcp Enabled

清除 DNS 服務器設置:

Set-DnsClientServerAddress –InterfaceAlias Ethernet0 -ResetServerAddresses

並重新啟動網絡適配器以自動從 DHCP 服務器獲取 IP 地址:

Restart-NetAdapter -InterfaceAlias Ethernet0

如果您之前配置了默認網關,請將其刪除:

Set-NetIPInterface -InterfaceAlias Ethernet0| Remove-NetRoute -Confirm:$false

如果您需要重置計算機網絡接口的所有 IPv4 設置並將其切換為從 DHCP 獲取動態 IP 地址,請使用以下腳本:

$IPType = "IPv4"
$adapter = Get-NetAdapter | ? {$_.Status -eq "up"}
$interface = $adapter | Get-NetIPInterface -AddressFamily $IPType
If ($interface.Dhcp -eq "Disabled") {
If (($interface | Get-NetIPConfiguration).Ipv4DefaultGateway) {
$interface | Remove-NetRoute -Confirm:$false
}
$interface | Set-NetIPInterface -DHCP Enabled
$interface | Set-DnsClientServerAddress -ResetServerAddresses
}

使用 PowerShell 在多台計算機上遠程更改 DNS 和 IP 地址

您可以使用 PowerShell 遠程更改多台遠程計算機上的 IP 地址或 DNS 服務器設置。

假設您的任務是更改特定 AD 組織單位 (OU) 中所有 Windows Server 主機上的 DNS 設置。以下腳本使用 Get-ADComputer cmdlet 從 Active Directory 獲取計算機列表,然後通過 WinRM 連接到遠程計算機(使用 Invoke-Command cmdlet):

$Servers = Get-ADComputer -SearchBase ‘OU=Servers,OU=Berlin,OU=DE,DC=woshub,DC=cpm’ -Filter '(OperatingSystem -like "Windows Server*")' | Sort-Object Name
ForEach ($Server in $Servers) {
Write-Host "Server $($Server.Name)"
Invoke-Command -ComputerName $Server.Name -ScriptBlock {
$NewDnsServerSearchOrder = "192.168.2.11","8.8.8.8"
$Adapters = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {$_.DHCPEnabled -ne 'True' -and $_.DNSServerSearchOrder -ne $null}
Write-Host "Old DNS settings: "
$Adapters | ForEach-Object {$_.DNSServerSearchOrder}
$Adapters | ForEach-Object {$_.SetDNSServerSearchOrder($NewDnsServerSearchOrder)} | Out-Null
$Adapters = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {$_.DHCPEnabled -ne 'True' -and $_.DNSServerSearchOrder -ne $null}
Write-Host "New DNS settings: "
$Adapters | ForEach-Object {$_.DNSServerSearchOrder}
}
}