Remotely Update DNS Configuration

PowerShell Scripting Uncategorized

Here is a script you can use from PowerShell to change DNS configuration on remote systems. It takes a CSV file for input of which systems to change and which DNS servers to set.

This assumes the required NIC that needs to be updated is the only NIC that has an IP address and DNS server(s) assigned. Requires appropriate firewall ports to be open to remotely configure.

$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
$Computers = Import-Csv -Path "$ScriptDir\Computers.csv"

foreach ($Computer in $Computers) {
	write-host "$($Computer.ComputerFqdn): " -ForegroundColor Yellow
	if ($Computer.Dns4) {
		$NewDNSServers = $Computer.Dns1, $Computer.Dns2, $Computer.Dns3, $Computer.Dns4
	} elseif ($Computer.Dns3) {
		$NewDNSServers = $Computer.Dns1, $Computer.Dns2, $Computer.Dns3
	} elseif ($Computer.Dns2) {
		$NewDNSServers = $Computer.Dns1, $Computer.Dns2
	} elseif ($Computer.Dns1) {
		$NewDNSServers = $Computer.Dns1
	} else {
		$NewDNSServers = $null
	}
	
	if ($NewDNSServers) {
		Invoke-Command -ComputerName $Computer.ComputerFqdn -ScriptBlock {
			switch ($Args.Count) {
				1 {$NewDNSServers = @($($Args[0]))}
				2 {$NewDNSServers = @($($Args[0]), $($Args[1]))}
				3 {$NewDNSServers = @($($Args[0]), $($Args[1]), $($Args[2]))}
				4 {$NewDNSServers = @($($Args[0]), $($Args[1]), $($Args[2]), $($Args[3]))}
				default {$NewDNSServers = $null}
			}

			# Get the NIC(s) with an IP address and DNS servers assigned.
			$Adapters = gwmi Win32_NetworkAdapterConfiguration | where-object {$_.IpAddress -ne $null -and $_.DNSServerSearchOrder -ne $null}

			# Show current DNS servers.
			write-host "Before: " -ForegroundColor Green
			$Adapters | select-object -property @{Name="NIC"; Expression={$_.Description}}, DnsServerSearchOrder

			# Update DNS servers.
			$Adapters | foreach-object {$_.SetDnsServerSearchOrder($NewDNSServers)} | Out-Null
		
			# Show new DNS servers.
			$Adapters = gwmi Win32_NetworkAdapterConfiguration | where-object {$_.IpAddress -ne $null -and $_.DNSServerSearchOrder -ne $null}
			write-host "After: " -ForegroundColor Green
			$Adapters | select-object -property @{Name="NIC"; Expression={$_.Description}}, DnsServerSearchOrder
		} -ArgumentList $NewDNSServers
	} else {
		write-host "Skipping host $($Computer.ComputerFqdn) -- no DNS servers listed." -ForegroundColor Yellow
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *