DonationCoder.com forum
 
Read-only archive. This is a static copy of the DonationCoder.com forum. Reading and searching work as before; logging in, posting and private messages do not.
Archive of 2026-10-21 · About this archive · Main site

Author Topic: [Powershell] Update DNS for your chosen network adapter  (Read 9,912 times)

justice

  • Solve issues simply.
  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 1,898
    • Participated in NANY Challenge Four Times
    • Cody Award
    • Coding Snacks
    • DJ Badge - DJ
[Powershell] Update DNS for your chosen network adapter
« on: November 28, 2013, 11:45 AM »
I've got a bunch of pcs needing their DNS updated to Open DNS so here's a powershell script that will let you choose a network adapter and then set the DNS servers.
OpenDNS servers are provided. The script will make sure to run itself as admin.

Code
# 1.001
$servers = "208.67.222.222", "208.67.220.220"

# Functions 
function IsAdmin() {
	$wid     = [System.Security.Principal.WindowsIdentity]::GetCurrent()
	$prp     = new-object System.Security.Principal.WindowsPrincipal($wid)
	$adm     = [System.Security.Principal.WindowsBuiltInRole]::Administrator
	$IsAdmin = $prp.IsInRole($adm)
	$IsAdmin

}

function SetDNSForNIC($s, $n) {
	$dns = $n.DNSServerSearchOrder | Foreach {"$($_)"}
	$description = $NIC.Description
	Write-Host "OLD DNS settings for $description = $dns"

	$NIC.SetDNSServerSearchOrder($s) | out-null

	Write-Host "NEW DNS settings for $description = $s"
}

# Init
if (IsAdmin)
{
	(get-host).UI.RawUI.Backgroundcolor="DarkRed"
	clear-host
	$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration -computername . | where{$_.IPEnabled -eq $true} 

	$i = 1
	$message = $choices = $nic_descriptions = @()
	Foreach ($NIC in $NICs) {
		$d = $NIC.Description
		$nic_descriptions += $d
		$message += "$i - $d`n" 
		$choices += New-Object System.Management.Automation.Host.ChoiceDescription "&$i", "Select $d."
		$i = $i + 1
	}   
	$options = [System.Management.Automation.Host.ChoiceDescription[]]($choices)

	$title = "Select Adapter to Update DNS Settings for:"
	$result = $host.ui.PromptForChoice($title, $message, $options, 0) 

	$nic_descriptions[$result]
	# exit

	Foreach ($NIC in $NICs) {
		If ($NIC.Description  -eq $nic_descriptions[$result] ) {
			SetDNSForNIC $servers $NIC
		}
	}   
	Write-Host "Press any key to continue ..."
	$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

}   
Else {
	$this_script = $MyInvocation.MyCommand.Path
	Start-Process "$psHome\powershell.exe" -Verb Runas -ArgumentList "-command `"$this_script`""
}

Network adapters are listed by Description, this is listed in the Network Connection Details.
I would have used the NetConnectionID but not everyone will have named their network connection.
« Last Edit: November 28, 2013, 01:23 PM by justice »

Original address: https://www.donationcoder.com/forum/index.php?topic=36634.0