Created
September 22, 2016 17:13
-
-
Save Stephanevg/24f69ddbd340034a9353b77fbeee57d7 to your computer and use it in GitHub Desktop.
Replaces a network ip address / gateway (instead of adding a new one)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Replace-NetIpAddress{ | |
[cmdletbinding()] | |
Param( | |
[int]$interfaceIndex, | |
[IPaddress]$NewIp, | |
[int]$Prefix, | |
[IPaddress]$Gateway | |
) | |
$IpParams = @{} | |
$CurrentIpConf = Get-NetIPConfiguration -InterfaceIndex $interfaceIndex | |
if ($CurrentIpConf.IPv4Address.IPAddress -ne $NewIp){ | |
$IpParams.add('InterfaceIndex', $interfaceIndex) | |
$IpParams.add('IPAddress',$NewIp) | |
$IpParams.Add('PrefixLength' ,$Prefix) | |
$Adapter = Get-NetAdapter -InterfaceIndex $interfaceIndex | |
$Adapter | Remove-NetIPAddress -Confirm:$false | Out-Null | |
}else{ | |
Write-Warning "The ip $($NewIp) is already set." | |
} | |
if ($Gateway){ | |
$CurrentGateway = ($CurrentIpConf).Ipv4DefaultGateway.nexthop | |
if ($CurrentGateway -ne $Gateway){ | |
Get-NetRoute -InterfaceIndex $interfaceIndex -NextHop $CurrentGateway | Remove-NetRoute -Confirm:$false | |
$IpParams.add('DefaultGateway',$Gateway) | |
} | |
write-warning "Gateway $($Gateway) is already existing." | |
} | |
if ($IpParams.count -gt 0){ | |
New-NetIPAddress @IpParams | |
}else{ | |
Write-Warning "Ip configuration is identical as before" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment