Skip to content

Instantly share code, notes, and snippets.

@DrJume
Last active October 14, 2021 12:04
Show Gist options
  • Save DrJume/66d8662db29840a10d02f332ef885cd8 to your computer and use it in GitHub Desktop.
Save DrJume/66d8662db29840a10d02f332ef885cd8 to your computer and use it in GitHub Desktop.
Windows set/reset DNS servers for active network interface
[int]$mainIfIndex = Get-NetRoute -DestinationPrefix '0.0.0.0/0', '::/0' |
Sort-Object -Property { $_.InterfaceMetric + $_.RouteMetric } |
Select-Object -First 1 |
% {$_.ifIndex}
echo $mainIfIndex
@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
@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
@DrJume
Copy link
Author

DrJume commented Aug 8, 2021

File Description
Set_DNS_servers_for_active_network_interface.bat Set the DNS servers for the main Windows network interface to Cloudflare's servers.
reset_DNS_servers_for_active_network_interface.bat Reset the DNS servers to the ones provided by DHCP from the network router. This is very useful for the setup of lancache.
get_active_network_interface_index.ps1 PowerShell script for determining the active network interface.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment