Reputation: 2076
I am looking for a Powershell command that disables DHCP and sets the machine's private IP as a static IP; basically, I'm looking for the Powershell equivalent of following actions in the UI.
Control panel -> Network and Sharing Center -> Ethernet -> Properties -> IPv4 -> Properties -> toggle off "Obtain an IP address automatically" and toggle on "Use the following IP address" -> fill out IPv4 address, default gateway, and subnet mask.
The following commands, taken from this guide, seems to describe what I'm after, but Remove-NetIPAddress
results in kicking me off the server and locking me out.
$IP = "10.10.10.10"
$MaskBits = 24 # This means subnet mask = 255.255.255.0
$Gateway = "10.10.10.1"
$Dns = "10.10.10.100"
$IPType = "IPv4"
# Retrieve the network adapter that you want to configure
$adapter = Get-NetAdapter | ? {$_.Status -eq "up"}
# Remove any existing IP, gateway from our ipv4 adapter
If (($adapter | Get-NetIPConfiguration).IPv4Address.IPAddress) {
$adapter | Remove-NetIPAddress -AddressFamily $IPType -Confirm:$false
}
If (($adapter | Get-NetIPConfiguration).Ipv4DefaultGateway) {
$adapter | Remove-NetRoute -AddressFamily $IPType -Confirm:$false
}
# Configure the IP address and default gateway
$adapter | New-NetIPAddress `
-AddressFamily $IPType `
-IPAddress $IP `
-PrefixLength $MaskBits `
-DefaultGateway $Gateway
I'm unable to create a new IPv4 address so long as the existing one is still around, but removing the existing one borks the connection to the server.
Upvotes: 2
Views: 860
Reputation: 8868
That is incorrect. You can set multiple IPs on the same interface. So you simply add the new one with New-NetIPAddress
and then remove the previous one.
$currentIP = Get-NetIPAddress | where ipaddress -eq '192.168.43.96'
New-NetIPAddress -InterfaceAlias $currentIP.InterfaceAlias -IPAddress 192.168.43.20 -PrefixLength 24
Remove-NetIPAddress -InterfaceAlias $currentIP.InterfaceAlias -IPAddress $currentIP.IPAddress
The DNS and Gateway are separate things. Just don't change those if you don't need to. To avoid the confirmation prompt, simply add -Confirm:$false
to the Remove-NetIPAddress
command.
Upvotes: 2