Set network interface IP address with Powershell

The Problem

While setting up our partner technology centre recently, I found myself switching back and forth between networks so often that I was constantly having to change my laptop’s IP address. For reasons that are outside the scope of this article I’m unable to use the option for an alternate network configuration.

Powershell to the rescue

The solution? Two small Powershell scripts – one to setup my network connection for our corporate LAN, the other to setup my network connection for the PTC. The scripts are shown below – feel free to use them in any way you like.

PTC configuration script {#ptcconfigurationscript}

 $index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq “Local Area Connection”}).InterfaceIndex $NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index} $NetInterface.EnableStatic(“10.0.0.10”, “255.255.255.0”) $NetInterface.SetDynamicDNSRegistration(“FALSE”) 

Corporate LAN configuration script

This script just resets the network adapter back to DHCP

 $index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq “Local Area Connection”}).InterfaceIndex $NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index} $NetInterface.EnableDHCP() $NetInterface.SetDynamicDNSRegistration(“TRUE”) 

Extra stuff

Although I don’t need them in my PTC environment (it’s internal only, with no internet access), you can also use the snippets below to add some extra functionality. Set gateway:

 $NetInterface.SetGateways($gateway) 

Set DNS server search order:

 $NetInterface.SetDNSServerSearchOrder($dns) # (e.g. “10.10.1.1” for single server or “10.10.1.1,10.10.1.2” for multiple servers) 

Enable dynamic DNS registration (e.g. in AD environment):

 $NetInterface.SetDynamicDNSRegistration($registerDns)