This script can be used to set the DNS servers on all network adapters to DHCP. The change will only be made to adapters that are using DHCP for the IP address; adapters that have a static IP configured will not have the DNS settings modified.
# This script will loop over the available network adapters and change the DNS servers setting to DHCP.
# If the adapter does not have DHCP enabled (eg. it has a static IP address) the DHCP servers will not be changed.
# The script should be ran on startup.
#Requires -RunAsAdministrator
Write-Host -ForegroundColor Gray 'Getting list of network adapters from WMI which have DNS servers configured and DHCP enabled...'
$adapters = $null
try {
$adapters = Get-WmiObject Win32_NetworkAdapterConfiguration -ErrorAction Stop | Where-Object { ($_.DNSServerSearchOrder) -and ($_.DHCPEnabled -eq $true) }
}
catch {
$message = $_.Exception.message
Write-Error 'Error getting list of network adapters with DHCP enabled'
throw $message
}
# Check there is a result
if ( $adapters -eq $null ) {
Write-Error 'Error getting list of network adapters with DHCP enabled'
exit
}
if ( $adapters.count -eq 0 ) {
Write-Host -ForegroundColor Green 'No interfaces to re-configure'
exit
}
# Loop over each adapter and set to DHCP
$adapters | ForEach-Object {
$name = $_.Description
$index = $_.InterfaceIndex
Write-Host -ForegroundColor Yellow "Removing defined DNS servers for adapter $($name) (interfaceindex $($index))"
try {
Set-DnsClientServerAddress -InterfaceIndex $index -ResetServerAddresses -ErrorAction Stop
Write-Host -ForegroundColor Green "Configured adapter $($name) (interfaceindex $($index))"
}
catch {
$message = $_.Exception.message
Write-Error "Error configuring adapter $($name) (interfaceindex $($index)):"
Write-Error $message
}
}
Write-Host -ForegroundColor Gray 'Done'