Last active
October 14, 2021 12:04
-
-
Save DrJume/66d8662db29840a10d02f332ef885cd8 to your computer and use it in GitHub Desktop.
Windows set/reset DNS servers for active network interface
This file contains 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
[int]$mainIfIndex = Get-NetRoute -DestinationPrefix '0.0.0.0/0', '::/0' | | |
Sort-Object -Property { $_.InterfaceMetric + $_.RouteMetric } | | |
Select-Object -First 1 | | |
% {$_.ifIndex} | |
echo $mainIfIndex |
This file contains 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
@echo off | |
FOR /F "tokens=* USEBACKQ" %%F IN (`powershell "Get-NetRoute -DestinationPrefix '0.0.0.0/0', '::/0' | Sort-Object -Property { $_.InterfaceMetric + $_.RouteMetric } | Select-Object -First 1 | %% {$_.ifIndex}"`) DO ( | |
SET mainIfIndex=%%F | |
) | |
ECHO %mainIfIndex% | |
powershell "Set-DNSClientServerAddress -InterfaceIndex %mainIfIndex% -ResetServerAddresses" | |
ipconfig /flushdns | |
powershell "Get-DnsClientServerAddress -InterfaceIndex %mainIfIndex%" | |
pause |
This file contains 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
@echo off | |
FOR /F "tokens=* USEBACKQ" %%F IN (`powershell "Get-NetRoute -DestinationPrefix '0.0.0.0/0', '::/0' | Sort-Object -Property { $_.InterfaceMetric + $_.RouteMetric } | Select-Object -First 1 | %% {$_.ifIndex}"`) DO ( | |
SET mainIfIndex=%%F | |
) | |
ECHO %mainIfIndex% | |
powershell "Set-DNSClientServerAddress -InterfaceIndex %mainIfIndex% -ServerAddresses ('1.1.1.1','1.0.0.1')" | |
powershell "Set-DNSClientServerAddress -InterfaceIndex %mainIfIndex% -ServerAddresses ('2606:4700:4700::1111','2606:4700:4700::1001')" | |
ipconfig /flushdns | |
powershell "Get-DnsClientServerAddress -InterfaceIndex %mainIfIndex%" | |
pause |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Set_DNS_servers_for_active_network_interface.bat
reset_DNS_servers_for_active_network_interface.bat
get_active_network_interface_index.ps1
The function of the two
.bat
files can be implemented easier in PowerShell directly. But on some Windows machines direct execution of PowerShell script files is disabled. This is why I wrapped it all in Windows Batch files. The for-loop is only a workaround for getting the main interface index out of the PowerShell call.