Script to Change DNS Servers on Remote Server
I am new to powershell and I am trying to construct a script to change the DNS servers settings on a whole list of machines remotely. I have the list of machines that I want to change in a txt file. I have read several posts on this and tried several different
methods but I cannot seem to get it to work. Here is my code, any help is much appreciated.
$servers = Get-Content C:\PathToFile\computers.txt
foreach($server in $servers)
{
Write-Host "Connect to $server..."
$nics = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $server -ErrorAction Inquire | Where{$_.IPEnabled -eq "TRUE"}
$newDNS = "10.1.1.1","10.2.2.2"
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
}
}
}
February 12th, 2013 9:26pm
When entering the 'DNSServerSearchOrder' command I receive the following message:
Cannot find an overload for "SetDNSServerSearchOrder" and the argument count: "2".
At line:1 char:29
+ $wmi.SetDNSServerSearchOrder <<<< ("10.0.0.15", "255.255.255.0")
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
February 13th, 2013 1:59pm
Check this out. Working fine for me.
$computer = get-content C:\azam\sl.txt
$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration -computername $computer |where{$_.IPEnabled -eq TRUE}
Foreach($NIC in $NICs) {
$DNSServers = 198.102.234.125",198.102.234.126"
$NIC.SetDNSServerSearchOrder($DNSServers)
$NIC.SetDynamicDNSRegistration(TRUE)
}
Thanks
Azam
Please mark As answered if answered your question or helpful if helped
February 13th, 2013 2:52pm
Still not working for some reason. Does it matter that the DNS servers settings are already set. What I mean is that I am using the script to replace the DNS server settings that are already configured. Here are the results when I run the script:
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 91
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 91
February 13th, 2013 3:19pm
The account that I am logged in as is a member of the local Admin group. Do I have to add something to the script so that it runs as my account instead of a system account.
February 13th, 2013 3:50pm
What Os?
Are you able to change manually?
February 13th, 2013 3:56pm
Windows Server 2008 R2. Yes I am able to change manually. I'm guessing the script is running as a built in account as opposed to the account that I am logged in with.
February 13th, 2013 4:09pm
Right Click Powershell under programs\accessories\powershell and "Run as Administrator"
February 13th, 2013 4:20pm
Ok, finally got it working. You were right it was permissions. First thing I had to change was change the "Power Shell Execution Policy." I ran the command Get-ExecutionPolicy and it returned 'RemoteSigned' meaning that it would only run scripts that were
remotely signed. I then ran the command "Set-ExecutionPolicy Unrestricted" and the script worked. I had to start powershell using the 'Run as Administrator' option to change the Execution Policy. Thanks for your help!
February 13th, 2013 7:15pm
Now that I have the ability to change the DNS settings, it would be nice to write a script to run before which lists the DNS servers for a list of servers specified in text file. I would also run the script after I change the DNS servers so that I can
verify that they were all changed properly.
February 13th, 2013 8:41pm
A single liner would do --
$sl = get-content (text file path)
Get-WmiObject win32_networkadapterconfiguration -computername $sl -Filter "IPEnabled = 'True'" | select dnshostname,dnsserversearchorder | ft -autosize | out-file -filepath F:\sl.csv
February 14th, 2013 4:56am
I have added the above command to my script. I able to get the DNS Servers and change the DNS servers on the local machine (where I am running the script from) but when I try and add remote systems to the list it comes up blank. Could the ExecutionPolicy
on the remote server be preventing me from gathering the NIC information or does that setting only apply on the machine where you launch the script?
February 14th, 2013 3:55pm
Nope...Executionpolicy needs to be on the server from which you are trying to execute the script.
Not required on all the servers which you are running against.
Please make sure you have the credentails which have access to the servers against which you are running the script.
For making any changes you should be having admin privileges on the server against which you are running the script.
February 14th, 2013 4:33pm
Can I add a 'run as' command to my script? Got one?
February 14th, 2013 4:39pm
You can use -credential parameter...please work on it and let us know...if you still finding an issue.
Get-WmiObject [-Authority <string>] [-Amended] [-AsJob] [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges]
[-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-ThrottleLimit <int>] [<CommonP
arameters>]
You can always use
get-help "command" -full ( its shows the examples too associated with the command)
February 15th, 2013 8:06am
This is turning into a very useful script. I tried running it on a list of development servers and it got hung up on something. Eventually I realized that several of the systems were not even pingable which is probably why it was unable to collect the
DNS information. I would like to set this up so that it first pings each system and if that is successful it attempts to collect the DNS information. If it is unable to ping the system I would like it to just write the system name to a text file so I have
a list of systems that it was unable to reach. Thanks again!
February 25th, 2013 4:39pm
Here is what I have, but it's not working. When I run it, it completes but it doesn't follow the if/else command properly it just run through all commands for all systems listed in the text file:
Foreach ($strComputer in get-content "C:\Data\Scripts\Working\ServerList1.txt")
{
if (test-connection $strComputer -quiet)
{
$c.Cells.Item($intRow,1) = $strComputer
$strWMI = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -computer $strcomputer -ErrorAction Stop | `
Where-Object {$_.IPEnabled -eq $TRUE -and $_.DHCPEnabled -eq $False}
Foreach ($ip in $strWMI)
{
$c.Cells.Item($intRow,2) = $ip.DHCPEnabled
$c.Cells.Item($intRow,3) = $ip.IPAddress
$c.Cells.Item($intRow,4) = "$($ip.DNSServerSearchOrder[0])"
$c.Cells.Item($intRow,5) = "$($ip.DNSServerSearchOrder[1])"
$intRow = $intRow + 1
}
}
$d.EntireColumn.AutoFit()
else
{
write-output "Cannot connect to $strComputer" | out-file C:\Data\scripts\results.txt}}
Write-Host "Press any key to continue ..."
February 26th, 2013 5:05pm
***HOLY GOD DID THIS SCREW UP MY SERVER***
I was looking to exactly as the submitter - however I tested this out on a a Windows 2008R2 box and the NIC was then hosted. Couldn't ping, the box wouldn't ever come up to a login screen. Only fortunately since this was a VM in ESXi was I able to remove
the NIC, reboot, add a new nic with new settings and wha'la' - working again.
For whatever reason, I had disasterours results with this script.
*Backup up or Snapshot a Test box before running this*
August 8th, 2013 3:12pm
***HOLY GOD DID THIS SCREW UP MY SERVER***
I was looking to exactly as the submitter - however I tested this out on a a Windows 2008R2 box and the NIC was then hosted. Couldn't ping, the box wouldn't ever come up to a login screen. Only fortunately since this was a VM in ESXi was I able to remove
the NIC, reboot, add a new nic with new settings and wha'la' - working again.
For whatever reason, I had disasterours results with this script.
*Backup up or Snapshot a Test box before running this*
Um.
You're running code you don't understand from strangers on the internet.
Consider this a life lesson.
August 8th, 2013 3:56pm
I have tried running the script from mohdazam89 on a several test machines. At first it seems to do its job pretty well... the only thing is that the servers are now taking for ever to boot. It takes a very long time before it is done with applying
computer settings and it also takes a long time to log on as administrator.
I have double checked the DNS servers, and they are OK. The script from mohdazam89 in some way seems to screw up the network card/performance whatsoever. I am pretty familiar with Power-shell and I do not see any harmful code in this script.
Any idea why this makes the server take a long time to boot and the logon take a long time to complete? Or better yet a script that does not cause this behavior.
We are in the process of decommissioning a few DNS servers, and it would be very handy to have a script that could change the DNS server settings on the network adapters remotely. Logging on to more than 200 servers and changing the settings
manually is a very cumbersome job... The majority of the servers are running Windows 2008 R2 SP1.
A little more useful answer than the one from Mike Laughlin.... is much more appreciated
-
Edited by
Erik Nettekoven
Thursday, October 17, 2013 4:28 PM
October 17th, 2013 4:26pm
I have tried running the script from mohdazam89 on a several test machines. At first it seems to do its job pretty well... the only thing is that the servers are now taking for ever to boot. It takes a very long time before it is done with applying
computer settings and it also takes a long time to log on as administrator.
I have double checked the DNS servers, and they are OK. The script from mohdazam89 in some way seems to screw up the network card/performance whatsoever. I am pretty familiar with Power-shell and I do not see any harmful code in this script.
Any idea why this makes the server take a long time to boot and the logon take a long time to complete? Or better yet a script that does not cause this behavior.
We are in the process of decommissioning a few DNS servers, and it would be very handy to have a script that could change the DNS server settings on the network adapters remotely. Logging on to more than 200 servers and changing the settings
manually is a very cumbersome job... The majority of the servers are running Windows 2008 R2 SP1.
A little more useful answer than the one from Mike Laughlin.... is much more appreciated
-
Edited by
Erik Nettekoven
Thursday, October 17, 2013 4:28 PM
October 17th, 2013 4:26pm
A little more useful answer than the one from Mike Laughlin.... is much more appreciated
Start up a new thread, post your code and your errors, and we'll help you work through your issues.
My answer is quite useful. If you don't understand a script, don't run it. That is always good advice.
October 17th, 2013 5:19pm
My answer is quite useful. If you don't understand a script, don't run it. That is always good advice.
October 18th, 2013 7:27am
Don't run with scissors or don't eat yellow snow is also always good advice, but it does not contribute in any way to the actual problem/question. You can post your advice with every question asked in this forum, but it does not solve any thing.
That other thread hijacker didn't bother to ask a question or try to fix the script in question, so he got advice instead.
October 18th, 2013 1:15pm
Note that I tried doing something similar. It worked great. But after a while some servers lost their DNS entries making them unreachable by name. We could solve this by rebooting the server after which it worked well again.
The problem occured once for most of the servers. Not sure why. Probably, some credentials issue with the record in the DNS.
March 25th, 2014 10:17am
This script is very helpful. Thanks!
How about changing the "secondary" DNS only? I wanted to keep the primary DNS configured.
August 20th, 2015 10:10am
This script is very helpful. Thanks!
How about changing the "secondary" DNS only? I wanted to keep the primary DNS configured.
In the script just fill in the ip address of the current primary DNS as first in the variable
$DNSServers = <IPCurrentPrimaryDNSServer>",<IPOfNewSecondary>"
August 20th, 2015 10:32am
Thanks Erik.. I appreciate it.
Another problem. I have several servers with multiple NICs. When i tried to run/test the scripts in this forum, it changes all the DNS settings of all the enabled NICS. I wanted to change only one NIC.
So, what I did was get all NIC names of the adapters. (Example of a NIC name: Local Area Connection)
My problem now is getting a new script to change the DNS settings of remote computers of a specific NIC only.
I can do it locally using the script below, but i can't make it work through remote.
Set-DnsClientServerAddress -InterfaceAlias Ethernet -ServerAddresses "1.1.1.1","2.2.2.2"
Thanks in advance.
August 26th, 2015 9:41am