Skip to content

Instantly share code, notes, and snippets.

@elico
Created June 5, 2024 20:56
Show Gist options
  • Save elico/724a19980fbf3fc94ebe27022fe16ebc to your computer and use it in GitHub Desktop.
Save elico/724a19980fbf3fc94ebe27022fe16ebc to your computer and use it in GitHub Desktop.
Set a static address on a specific interface with specific ip string prefix
# Variables
$ipStringPrefix = "192.20.20." # Replace with the desired IP address prefix
$newIpAddress = "192.20.20.150" # Replace with the desired new static IP address
$newPrefixLength = 24 # Replace with the desired subnet mask length
# Find the interface by CIDR
$interfaces = Get-NetIPAddress | Where-Object {
$_.IPAddress.StartsWith($ipStringPrefix)
}
if ($interfaces -and $interfaces.Count -gt 0) {
$interfaceName = $interfaces[0].InterfaceAlias
Write-Output "Found interface: $interfaceName"
# Remove existing IP address configuration to avoid conflicts
$interfaces | ForEach-Object {
Remove-NetIPAddress -InterfaceAlias $interfaceName -IPAddress $_.IPAddress -Confirm:$false
}
# Reset the interface to use DHCP for both IP and DNS
Set-NetIPInterface -InterfaceAlias $interfaceName -Dhcp Enabled
Set-DnsClientServerAddress -InterfaceAlias $interfaceName -ResetServerAddresses
Write-Output "DHCP CLient set on interface $interfaceName"
} else {
Write-Output "No interface found with prefix $ipStringPrefix"
}
# Variables
$ipStringPrefix = "192.20.20." # Replace with the desired IP address prefix
$newIpAddress = "192.20.20.150" # Replace with the desired new static IP address
$newPrefixLength = 24 # Replace with the desired subnet mask length
# Find the interface by CIDR
$interfaces = Get-NetIPAddress | Where-Object {
$_.IPAddress.StartsWith($ipStringPrefix)
}
if ($interfaces -and $interfaces.Count -gt 0) {
$interfaceName = $interfaces[0].InterfaceAlias
Write-Output "Found interface: $interfaceName"
# Remove existing IP address configuration to avoid conflicts
$interfaces | ForEach-Object {
Remove-NetIPAddress -InterfaceAlias $interfaceName -IPAddress $_.IPAddress -Confirm:$false
}
# Reset the interface to use DHCP for both IP and DNS
Set-NetIPInterface -InterfaceAlias $interfaceName -Dhcp Enabled
Set-DnsClientServerAddress -InterfaceAlias $interfaceName -ResetServerAddresses
# Set static IP address without a default gateway
New-NetIPAddress -InterfaceAlias $interfaceName -IPAddress $newIpAddress -PrefixLength $newPrefixLength
# Configure DNS servers
# Set-DnsClientServerAddress -InterfaceAlias $interfaceName -ServerAddresses $dnsServers
Write-Output "Static IP address $newIpAddress/$newPrefixLength set on interface $interfaceName with DNS servers $($dnsServers -join ', ')"
} else {
Write-Output "No interface found with prefix $ipStringPrefix"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment