4

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?

1

1 Answer 1

13

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I knew it was going to be something simple, but googling brought me no answers. Any ideas as to why Set-NetIPAddress doesn't include the ability to change the gateway?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.