Skip to content

Instantly share code, notes, and snippets.

@f-steff
Last active August 8, 2023 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save f-steff/ccbe360ee7963a912312c95805bed4ba to your computer and use it in GitHub Desktop.
Save f-steff/ccbe360ee7963a912312c95805bed4ba to your computer and use it in GitHub Desktop.

Powershell script to list active DNS servers according to access priority

The PowerShell script lists the DNS servers configured on the active network interfaces of a Windows system. It filters the network interfaces to include only those that are currently connected (status "Up") and retrieves the DNS server information for those interfaces. The output is sorted by interface metric, which reflects the priority of the interfaces, and includes the interface alias, interface metric, and DNS server IP addresses.

Usage

  1. Save the script as List-Prioritized-DNS-Servers.ps1.
  2. Navigate to the directory where the script is saved.
  3. Run the script using the command: .\List-Prioritized-DNS-Servers.ps1.

Output

The script outputs a table with the following columns:

  • InterfaceAlias: The name of the network interface.
  • InterfaceMetric: The metric of the network interface, reflecting its priority. Lower number have highest priority.
  • DnsServers: The IP addresses of the DNS servers associated with the interface.

Examples

InterfaceAlias InterfaceMetric DnsServers

Ethernet 5     20              192.168.8.1
Ethernet 5     20              192.168.8.2
Wi-Fi_Laptop   45              10.0.0.1
Wi-Fi_Laptop   45              1.1.1.1
Wi-Fi_Laptop   45              8.8.8.8
$connectedInterfaces = Get-NetAdapter | Where-Object { $_.Status -eq 'Up' }
$connectedInterfaces | ForEach-Object {
$interfaceAlias = $_.Name
$dnsServers = Get-DnsClientServerAddress -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4 | Select-Object -ExpandProperty ServerAddresses
$interfaceMetric = (Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex).InterfaceMetric | Select-Object -First 1
for ($i = 0; $i -lt $dnsServers.Count; $i++) {
[PSCustomObject]@{
InterfaceAlias = $interfaceAlias
InterfaceMetric = [string]$interfaceMetric
DnsServers = $dnsServers[$i]
Order = $i
}
}
} | Sort-Object InterfaceMetric, Order | Select-Object -Property InterfaceAlias, InterfaceMetric, DnsServers | Format-Table -AutoSize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment