Gary Henning
Gary Henning

Reputation: 80

Windows Powershell Set IP Address on network adapter

I need to be able to take my laptop and plug into several different networks across several locations. Each network requires I use a static address. I currently have a shell script that prompts for a network location and uses netsh to set the IP address. However, Microsoft is warning that they might remove netsh and to use Powershell so I'm trying to recreate my script in Powershell.

The problem I'm having is that if I go from dhcp to a static address I can use:

New-NetIPAddress -InterfaceAlias $myAdapter -AddressFamily IPv4 10.1.2.3 -PrefixLength 24 -Type Unicast -DefaultGateway 10.1.2.1

However, when going from a static address to another static address using New-NetIPAddress just adds another IP address to the adapter (and I cannot connect to anything as it appears to only use the first IP address). To get around that I can use Set-NetIPAddress, but that appears to not accept the -DefaultGateway parameter so I'm assigned the new address, but with the old gateway. I tried using Remove-NetIPAddress, but that appears to leave the gateway parameter so the New-NetIPAddress command fails with "Instance DefaultGateway already exists". How can I either remove the gateway so I can start over with New-NetIPAddress or replace the gateway when using Set-NetIPAddress?

Upvotes: 3

Views: 15927

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

Use Remove-NetRoute to remove the gateway:

# Remove the static ip
Remove-NetIPAddress -InterfaceAlias $myAdapter

# Remove the default gateway
Remove-NetRoute -InterfaceAlias $myAdapter

# Add the new IP and gateway
New-NetIPAddress -InterfaceAlias $myAdapter -AddressFamily IPv4 10.1.2.4 -PrefixLength 24 -Type Unicast -DefaultGateway 10.1.2.255

Upvotes: 12

Related Questions