topbanner_forum
  *

avatar image

Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
  • Friday March 29, 2024, 6:48 am
  • Proudly celebrating 15+ years online.
  • Donate now to become a lifetime supporting member of the site and get a non-expiring license key for all of our programs.
  • donate

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

justice

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 1,898
    • View Profile
    • Donate to Member
[Powershell] Update DNS for your chosen network adapter
« on: November 28, 2013, 05: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.

# 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, 07:23 AM by justice »