Last active
April 24, 2018 10:48
-
-
Save skunkie/365a8f62e144fd56be49546375e0906e to your computer and use it in GitHub Desktop.
Set static IP address from DHCP
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
$addressFamily = 'IPv4' | |
# Retrieve the network adapter | |
$adapters = Get-NetAdapter | Where-Object {$_.Status -eq 'Up'} | |
foreach ($adapter in $adapters) { | |
$ipConfiguration = $adapter | Get-NetIPConfiguration | |
if ($ipConfiguration.NetIPv4Interface.DHCP -eq 'Disabled') { | |
continue # 'DHCP is not enabled' | |
} | |
$dns = ($ipConfiguration | Get-DnsClientServerAddress -AddressFamily $addressFamily).ServerAddresses | |
# Remove any existing IPv4 IP and gateway from the adapter | |
if (($adapter | Get-NetIPConfiguration).IPv4Address.IPAddress) { | |
$adapter | Remove-NetIPAddress -AddressFamily $addressFamily -Confirm:$false | |
} | |
if (($adapter | Get-NetIPConfiguration).Ipv4DefaultGateway) { | |
$adapter | Remove-NetRoute -AddressFamily $addressFamily -Confirm:$false | |
} | |
# Configure the IP address and default gateway | |
$adapter | New-NetIPAddress ` | |
-AddressFamily $addressFamily ` | |
-IPAddress $ipConfiguration.IPv4Address.IPAddress ` | |
-PrefixLength $ipConfiguration.IPv4Address.PrefixLength ` | |
-DefaultGateway $ipConfiguration.IPv4DefaultGateway.NextHop | Out-Null | |
# Configure the DNS client server IP addresses | |
$adapter | Set-DnsClientServerAddress -ServerAddresses $dns | Out-Null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment