Switching between DHCP and static IP addresses is a common task for network administrators, but using the Windows GUI for this can be time-consuming. In this article, you’ll learn how to do it quickly using PowerShell commands.
Settings a Static IP Address
Before setting a static IP we need to disable DHCP on the interface. In my case it is called Ethernet 2
. This is the adapter name that shows up under Control Panel > Network Connections.
Get-NetIPInterface -InterfaceAlias "Ethernet 2" -AddressFamily "IPv4" | Set-NetIPInterface -Dhcp Disabled
Then, let’s say we want to set our interface to the static IP 192.168.97.100
with the default gateway 192.168.97.182
:
Get-NetIPInterface -InterfaceAlias "Ethernet 2" -AddressFamily "IPv4" | New-NetIPAddress -AddressFamily "IPv4" -IPAddress "192.168.97.100" -PrefixLength 24 -DefaultGateway 192.168.97.182
We can also assign multiple static IP addresses – this isn’t possible on the GUI but can be done with PowerShell by
Reset to Defaults – Enable DHCP
To reset the IP configuration of the interface to use DHCP use the following commands. Before we can set the interface to use DHCP is we need to remove all previously assigned IP addresses:
# Remove all previously assigned IP addresses
Get-NetIPAddress -InterfaceAlias "Ethernet 2" | Remove-NetIPAddress -Confirm:$false
Remove-NetRoute -InterfaceAlias "Ethernet 2" -DestinationPrefix "0.0.0.0/0" -Confirm:$false
# Set IP/DNS to DHCP
Set-NetIPInterface -InterfaceAlias "Ethernet 2" -AddressFamily "IPv4" -Dhcp Enabled
Set-DnsClientServerAddress -InterfaceAlias "Ethernet 2" -ResetServerAddresses
# Restart the interface (optional)
Disable-NetAdapter -Name "Ethernet 2" -Confirm:$false; Enable-NetAdapter -Name "Ethernet 2" -Confirm:$false
You may learn more PowerShell commands to manage your network at Microsoft’s NetAdapter documentation available here.