Skip to content

Instantly share code, notes, and snippets.

@LemonNekoGH
Created February 24, 2026 19:11
Show Gist options
  • Select an option

  • Save LemonNekoGH/c5da191ca49c53f0f0ea73f25b6a47d0 to your computer and use it in GitHub Desktop.

Select an option

Save LemonNekoGH/c5da191ca49c53f0f0ea73f25b6a47d0 to your computer and use it in GitHub Desktop.
ToggleDhcpOnWindows

ToggleDhcpOnWindows

A script to toggle DHCP and static IP for the first physical network adapter.

You can just copy they to your desktop, then double-click toogle-dhcp.bat to run it.

If you use PowerToys, you may be able to run it in PowerToys Run after your first click.

@echo off
set "scriptPath=%~dp0toggle-dhcp.ps1"
powershell -Command "Start-Process powershell -ArgumentList '-ExecutionPolicy Bypass -File \"%scriptPath%\"' -Verb RunAs"
$adapter = Get-NetAdapter -Physical | Select-Object -First 1
$ifIndex = $adapter.ifIndex
$staticIP = "<YourIP>"
$prefix = 24
$gateway = "<YourGateway>"
$dns = @("8.8.8.8", "8.8.4.4")
$status = Get-NetIPInterface -InterfaceIndex $ifIndex -AddressFamily IPv4
if ($status.Dhcp -eq "Enabled") {
Write-Host "DHCP detected. Switching to Static IP..." -ForegroundColor Cyan
Set-NetIPInterface -InterfaceIndex $ifIndex -DHCP Disabled
$oldRoute = Get-NetRoute -InterfaceIndex $ifIndex -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue
if ($oldRoute) {
Write-Host "Removing legacy gateway route..." -ForegroundColor Gray
$oldRoute | Remove-NetRoute -Confirm:$false
}
Remove-NetIPAddress -InterfaceIndex $ifIndex -AddressFamily IPv4 -Confirm:$false -ErrorAction SilentlyContinue
Set-DnsClientServerAddress -InterfaceIndex $ifIndex -ResetServerAddresses -ErrorAction SilentlyContinue
$timeout = 0
while ($timeout -lt 30) {
$existingRoute = Get-NetRoute -InterfaceIndex $ifIndex -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue
if (-not $existingRoute) { break } # Exit loop if gateway is gone
Write-Host "Waiting for Gateway to release... ($($timeout * 0.1)s)" -ForegroundColor Gray
Start-Sleep -Milliseconds 100
$timeout++
}
Start-Sleep -Milliseconds 100
New-NetIPAddress -InterfaceIndex $ifIndex -IPAddress $staticIP -PrefixLength $prefix -DefaultGateway $gateway -Confirm:$false
Set-DnsClientServerAddress -InterfaceIndex $ifIndex -ServerAddresses $dns
Write-Host "Success: Interface is now STATIC ($staticIP)" -ForegroundColor Green
}
else {
Write-Host "Static IP detected. Switching to DHCP..." -ForegroundColor Cyan
Set-NetIPInterface -InterfaceIndex $ifIndex -DHCP Enabled
Set-DnsClientServerAddress -InterfaceIndex $ifIndex -ResetServerAddresses
Write-Host "Success: Interface is now DHCP" -ForegroundColor Green
}
Write-Host "`nPress any key to exit..." -ForegroundColor Yellow
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment