Skip to content

Instantly share code, notes, and snippets.

@exeral
Last active August 28, 2024 03:22
Show Gist options
  • Save exeral/87c792d20262026318661fdc03ea8807 to your computer and use it in GitHub Desktop.
Save exeral/87c792d20262026318661fdc03ea8807 to your computer and use it in GitHub Desktop.
pull Windows DNS from WSL

content

there is two scripts:

  • powershell dns.ps1
  • bash dns.sh

how it works

the bash script dns.sh (ran from WSL) calls the powershell script dns.ps1 wich retrieves the DNS informations

you can write directly its output to resolv.conf (as root):

./dns.sh > /etc/resolv.conf

requirements

  • configure in dns.sh line 5 the absolute path to the powershell script
  • JQ is required : apt install jq
# Discover things and create an $Entries object.
$NetworkInterfaces = Get-NetIPInterface -AddressFamily IPv4 | Where-Object ConnectionState -EQ 'Connected' | Where-Object NlMtu -LT 9001
$DNSServerAddresses = Get-DnsClientServerAddress -AddressFamily IPv4
$DNSClients = Get-DnsClient
$Entries = $NetworkInterfaces | ForEach-Object {
[PSCustomObject]@{
'InterfaceAlias' = $_.InterfaceAlias
'InterfaceIndex' = $_.InterfaceIndex
'InterfaceMetric' = $_.InterfaceMetric
'DNSServerAddresses' = ($DNSServerAddresses | Where-Object InterfaceIndex -EQ $_.InterfaceIndex | Where-Object AddressFamily -EQ 2).ServerAddresses
'DNSSuffixes' = @(($DNSClients | Where-Object InterfaceIndex -EQ $_.InterfaceIndex).ConnectionSpecificSuffix) + @(($DNSClients).ConnectionSpecificSuffixSearchList | Out-Null)
}
} | Sort-Object InterfaceMetric -Unique
$array_suffixes = (Get-DnsClientGlobalSetting).SuffixSearchList
$array_servers = $Entries.DNSServerAddresses | select -Unique
$jsonBase = @{}
$jsonBase.Add("servers",$array_servers)
$jsonBase.Add("suffixes",$array_suffixes)
$jsonBase | ConvertTo-Json -Compress
#!/bin/bash
POWERSHELL=/mnt/c/WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe
JSON=$($POWERSHELL 'C:\Users\change-me!!\Documents\dns.ps1')
SUFFIXES=$(jq -r '.suffixes | join(",")' <<< "$JSON")
for server in $(jq -r '.servers[]' <<< "$JSON"); do
echo "nameserver $server"
done
echo "search $SUFFIXES"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment