|
$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") |