Configure Static IP Address or DHCP

The second post in my PowerShell Beginner series, “Daily Tasks, The PowerShell Way“. Learn how to get network connection information and configure a static IP or DHCP using PowerShell.

Are you connected?

In my previous post we covered how to use Test-NetConnection for network connectivity troubleshooting. If you connected to a DHCP enabled network, you will likely have successful tests without any action on your part. However, if your network environment requires static configuration of IP addresses and DNS servers for servers and/or workstations, you need to configure the correct network settings for a newly provisioned computer.

Get network connection details

First, let’s see what’s connected. Get-NetAdapter will return basic network information. We see network connection “Ethernet0” is up with a speed of 1Gbps.

We can use the cmdlet Get-NetIPInterface to get a summary table of our network interfaces and their connection state. Because I’m only concerned about IPv4, I include the parameter -AddressFamily IPv4. We can see that I have one physical interface connected “Ethernet0”, and it is currently configured for DHCP.

We can use the Get-NetIPConfiguration cmdlet to return IP information for “Ethernet0”. We learn the IPv4 address, the default gateway, and DNS servers. One thing that is absent from this result set is subnet mask, hopefully that will be added in the future. However, we can get the subnet mask as a prefix value if we run Get-NetIPAddress. You can see PrefixLength is 24 (/24 or 255.255.255.0).

Set static IP address

You may want to set a static IP if your computer is a server or need to set static IPs in an environment without DHCP. You can do this using the New-NetIPAddress cmdlet. This is equivalent to opening the Properties of a network connection and manually configuring the adapter.

If you manually inspect the adapter, you can verify the static IP information and DNS servers are set.

Reset network connection to DHCP

My demo computer is working with a static IP configuration, but now that I’m done I want to revert it back to its original DHCP configuration. To do that in PowerShell, I need to do three things:

Set the connection back to “Obtain an IP address automatically”

Remove the static default gateway

Set the connection back to “Obtain DNS server address automatically”

I can do this by running a sequence of three cmdlets, Set-NetIPInterface, Remove-NetRoute, and Set-DNSClientServerAddress. I will also incorporate Get-NetIPInterface and use piping to streamline the command input.