Remotely set DNS servers on Windows clients

One of the things that we do for our customers is to refresh their virtual environments with new servers (latest OS, etc). When we do this migration, we almost always replace the DNS servers. This can cause significant work to change existing (and new) servers to the new DNS IPs. Enter PowerShell!

<#
s e t D N S . p s 1 

Purpose:		Change the DNS servers on remote computers bases on list in a text file.
Author:			Michael Kenning <mjkenning@gmail.com>
Version: 		1.1 (16 NOV 2014)

Usage:			.\setDNS.ps1 [INPUT FILE]
Example: 		.\setDNS.ps1 .\file.txt

Requirements:
	1) PowerShell installed on executing machine
	2) Credentials: The executing user must have admin rights on the target machines

#>

param (
	[Parameter(Mandatory=$true,Position=0)]
	[ValidateNotNullOrEmpty()]
	[String]
	$path
)

$servers = Get-Content $path
$newDNS = "10.1.1.1","10.2.1.1"
 
foreach($server in $servers) {
	Write-Host "Connecting to $server..."
	$nics = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $server -ErrorAction Inquire | Where{$_.IPEnabled -eq "TRUE"}
	 
	foreach($nic in $nics) {
		Write-Host "`tExisting DNS Servers " $nic.DNSServerSearchOrder
		$x = $nic.SetDNSServerSearchOrder($newDNS)
	 
		if($x.ReturnValue -eq 0) {
			Write-Host "`tSuccessfully Changed DNS Servers on " $server
		}
		else {
			Write-Host "`tFailed to Change DNS Servers on " $server
		}
	}
}
Advertisements
Tagged with: , ,
Posted in Powershell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: