Script to add a DNS server on the client NIC card? And map a drive aswell?

I have a server running NT.

Each client machine has 2 DNS servers from our ISP.

I need to remove the primary one and update with another IP address, in a simple script that can be run when the users logs on.

How can this be done?



I would also like to know how I can run a script to map a network drive using an if else statement. First check if there is a drive assigned to "U". If yes, ignore script, If no add in the mapped drive. I know how to map a drive but dont know about if/else strings in these batch files.
LVL 5
georgecooldudeAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris DentPowerShell DeveloperCommented:

You can change the DNS IP Addresses with the VBScript below. It uses the Windows Managment Instrumentation to send the change request. So you'll need admin access over whatever you're running it on, and you'll need WMI there of course ;)

It can be altered to run on a group of computers, at present it would slot quite happily into a Logon Script and run from there.

' This script replaces the DNS Server Search List in the Network Adapter Configuration.
' It will only replace DNS values for Static configuration, and will not run against hosts
' configured by DHCP.

Option Explicit

' Variable Declaration

Dim objWMIService, objNICConfig
Dim strComputer, strDNSServer
Dim arrNewDNSServer
Dim colNICConfigs
Dim intSetDNSServers

' Main Script

' For strComputer . refers to the current computer
' arrNewDNSServer is an array containing DNS Server Addresses to add

strComputer = "."
arrNewDNSServer = Array("192.168.0.1", "192.168.0.2")

' Set up interface to WMI and select all Interfaces with IP Enabled

Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")

' For each Interface with IP Enabled set the new DNS Servers
 
For Each objNICConfig In colNICConfigs
      If objNICConfig.DHCPEnabled = FALSE Then
            intSetDNSServers = _
            objNICConfig.SetDNSServerSearchOrder(arrNewDNSServer)
            If intSetDNSServers = 0 Then
                  WScript.Echo "Replaced DNS server search order list."
            Else
                  WScript.Echo "Unable to replace DNS server search order list."
            End If
      End If
Next

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Chris DentPowerShell DeveloperCommented:

For the drive mapping you get lots more choice.

Visual Basic:

Option Explicit

Dim strDrive, strSharePath
Dim bolDrive

strDrive = "N:"
strSharePath = "\\server\share"

Set objNetwork = CreateObject("WScript.Network")
Set objFileSystem = CreateObject("Scripting.FilesystemObject")

bolDrive = objFileSystem.DriveExists(strDrive)

If (bolDrive = FALSE) Then
    objNetwork.MapNetworkDrive strDrive, strSharePath
End If

Kixtart:

If Exist("N:")
   Use "N:" "\\Server\Share"
EndIf

DOS:

@echo off
If Not Exist N: net use n: \\server\share
0
Chris DentPowerShell DeveloperCommented:

Oops... Kix bit above should be:

If Not Exist("N:")
   Use "N:" "\\Server\Share"
EndIf
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

map000Commented:
... or you can use dhcp for clients (dhcp server on the Nt server) and make changes when needed centralized and more flexible (from scope options)
for exemple you need to have all client computers running when you use scripts (dhcp will provide the setting at system startup)
also it's a better ideea to use your nt server as the Dns server for your clients (and configure it to forward queries to the ISP dns servers)
0
Chris DentPowerShell DeveloperCommented:

He's in the process of upgrading to Windows 2003, so the NT server will soon disapear ;)

I agree completely about setting up DHCP.
0
georgecooldudeAuthor Commented:
Chris thanks for your suggestions.

I will try the scripts out. On the DNS script:

"  WScript.Echo "Unable to replace DNS server search order list.""
How can I put in a prompt that requires the user to press enter? I would like to say. ...blah blah contact the IT department.

As you know I am migrating from NT. I thought this would be the best way to upgrade without having to go through every single office in the building updating computers. The upgrade has to be silent with users not knowing its happening.  It also occured I need to change the domain name from <NTdomainName> to <2003NewDomainName> - Can this be done in a script? That would require a reboot aswell. How can I automate the process of renaming the domain with as little input and disruption for the end users who only have the most basic of computer skills
0
georgecooldudeAuthor Commented:
map000, we are upgrading to 2003 so the NT box will soon be a lump of useless metal. (Sure there will be another role for it)

And I like the DHCP idea alot except I am not allowed to set that up until a later date.
0
Chris DentPowerShell DeveloperCommented:
Before anything else, can you confirm that the users are running Windows 2000 or XP?

Scripting re-joining a computer to a domain isn't advisable as you'd have to include in the script an account and password that has the permissions to do so.

For the DNS Script it's pretty flexible, any thoughts on how you want to run it?

Logon Script is slow but probably quite reliable.
Centrally is fast and allows greater flexibility in error reporting but might not catch everyone.

To answer the bit above, this will deal with it:

If intSetDNSServers = 0 Then
      MsgBox "Replaced DNS server search order list."
Else
      MsgBox "An error occurred while processing the script." & _
      " Please contact your System Administrator.",,"Error"
End If

If you didn't want to include the success message either then this will only print on error:

If not (intSetDNSServers = 0) Then
      MsgBox "An error occurred while processing the script." & _
      " Please contact your System Administrator.",,"Error"
End If
0
georgecooldudeAuthor Commented:
We are slowly upgrading our machines to XP Pro.

I think the following:

8 XP Pro machines
2 XP Home
10 Windows 2000 machines

And the rest range from:
Windows NT, 95, 98 and M.E.

Oh and 1 Apple Mac


We've 60-70 machines in total so it looks like the majority are running legacy systems. :(

Is there any way around having to go to each and every machine. I've been told this is something we would do as a very last resort.

0
Chris DentPowerShell DeveloperCommented:

Well we can but try... give me a little while.. I'll give you a script that can tell you which machines can and can't be changed automatically.

The Apple Mac I can't help you with at all though.
0
map000Commented:
Chris-Dent answered your question
you should give him the points and open a different thread (it's becoming too complex)
0
georgecooldudeAuthor Commented:
Well, I see it as an evoled thread. It has been assigned a max of 500 points because it is an "extremely difficult" question as said on the ask an expert page

"extremely difficult (500 points)"
"difficult (250 points)"

Creating multiply threads makes it hard to keep up with what was said where and you end up asking the same questions over again in.

Unless Chris would like to split the thread into a new one I'll leave it as it is.
0
Chris DentPowerShell DeveloperCommented:

Busy morning...

Not bothered about opening a new question for it. I already have a network scanner script, just a matter of ripping out some of it's more interesting features...

I haven't had time to alter it significantly though, but if you feed it a list of computer names (in a file called computers.txt) it'll try and connect to WMI on each  of them and give you a few bits of information in a results.txt file (semi-colon delimited text).

If you can't connect it'll tell you which, those will be the ones you have to run around changing things on.

It's written in Perl, so you'll need to download that from:

www.activestate.com

Then run it from the command line with perl wmi.pl

If you want to alter the Input / Output file names just edit them in the script itself.

#WMI.pl# (don't save the Start and End lines)

------------------------------------------Start------------------------------------------

#!/usr/bin/perl

# Computer Scanner Version 3.1.0
#
# Author: Chris Dent
# Last Modified: 29/09/2004


# Included Modules

use Net::Ping;
use Win32::OLE qw(in);

# Syntax Pragma

use strict;

# Debugging Options

# use warnings;
# use diagnostics;

# Global Variables

my $InputFile = "computers.txt";
my $OutputFile = "results.txt";

our (@ComputerList, @Input);
our ($Host, $PingHost);
our ($WMIUserName, $WMIOSName, $WMIComputerName);

# Functions and Subroutines

sub PingHost

# Pings the host by name and returns True or False

{
      my $PingObject = Net::Ping->new("icmp");
      if ($PingObject->ping($Host, 2))
      {
            $PingHost = 1;
      }
      else
      {
            $PingHost = 0;
      }
}

sub WMIConnect

# Connect to the Windows Management Instrumentation and try to grab
# Current User and OS Name

{
      my $WMIServices = Win32::OLE->GetObject("winmgmts:{impersonationLevel=impersonate,(security)}//$Host");
      my $ComputerSystem = $WMIServices->instancesof("Win32_ComputerSystem");
      foreach my $Data (in($ComputerSystem))
      {
            $WMIUserName = $Data->{UserName};
      }
      my $OperatingSystem = $WMIServices->instancesof("Win32_OperatingSystem");      
      foreach my $Data (in($OperatingSystem))
      {
            my $OSName = $Data->{Name};
            my @OSData = split(/\|/, $OSName);
            $WMIOSName = $OSData[0];
            $WMIComputerName = $Data->{CSName};
      }
}

sub CleanData

# Sub to Sort the Computer List from the original file data
# Requires extending to deal with multiple formats

{
      my $Counter = 0;
      
      foreach my $Line (@Input)
      {
            my @ComputerElement = split(/\t/, $Line);
            if ($ComputerElement[0] ne "\n")
            {
                  $ComputerList[$Counter] = $ComputerElement[0];
                  $Counter = ++$Counter;
            }
      }
}

sub ByNumber

# This sorts the elements in the hash (by port number in this case)
# Just makes the port scan run in numerical order

{
      if ( $a < $b )
      {
            -1
      }
      elsif ( $a > $b )
      {
            1
      }
      else
      {
            0
      }
}

# Main Script begins here

# Open Input File and Read Contents

open(INPUTFILE, "$InputFile") or die("Can't open $InputFile: $!");
@Input = <INPUTFILE>;
close(INPUTFILE);

# Open Output File for Writing (>) - a nice character delimited list
# Locks the file for exclusive access (you can't see it until it's done)

open(OUTPUTFILE, ">$OutputFile") or die("Can't open $OutputFile: $!");
flock(OUTPUTFILE, 2);

# Data cleaning - assumes data is tab delimited (default export from AD)
# or just a simple list, either way, it's going to chop off everything
# except the computer name

CleanData();

# Skip the first line - default export contains column names - Remove comment to enable (#)

# shift(@ComputerList);

# Dig out lots of information

foreach $Host (@ComputerList)
{
      chomp($Host);
      print "$Host";
      print OUTPUTFILE "Ping Name: $Host;";
      
      PingHost();
      if ($PingHost == 1)
      {
            print OUTPUTFILE "Ping Succeeded;";
      }
      else
      {
            print OUTPUTFILE "Ping Failed;";
      }
      
      if ($PingHost == 1)
      {
            eval { WMIConnect(); };
            if ($@)
            {
                  print ": WMI could not establish a connection";
                  print OUTPUTFILE ";;;"
            }
            else
            {
                  print OUTPUTFILE "$WMIOSName;";
                  print OUTPUTFILE "WMI Name: $WMIComputerName;";
                  print OUTPUTFILE "$WMIUserName;";
            }
            
      }
      else
      {
            print ": Unable to Ping Host";
      }
      print "\n";
      print OUTPUTFILE "\n";
}

close(OUTPUTFILE);

------------------------------------------End------------------------------------------
0
georgecooldudeAuthor Commented:
Thanks Chris,

This is easyier for me to read as I've got some basic php skills. I think perl is similar to php.

I'll give it a go and let you know how it works.
0
georgecooldudeAuthor Commented:
Do I just need perl installed on the server?


Oh and is it possible to control another machine from the command line? I found the following in another thread:
Say I open the command prompt but want to send the command down to a client machine. This is what I would send:

netdom join {COMPUTERNAME} /domain:{DOMAINNAME} /userd:{ADMINISTRATOR} /passwordd:{PASSWORD}

---

I'm trying to explore all options so I can put it forward to my head of department.
0
Chris DentPowerShell DeveloperCommented:

No, just perl installed wherever you run the script from.

Yes, you can use that command, but as I mentioned earlier you have to add the Administrator password in plain text, which makes it fair game for anyone. I would not recommend that approach.

At least with the "run around and do it manually" approach you know that it's done ;)
0
Chris DentPowerShell DeveloperCommented:

Oh sorry, misread that. No you can't control another machine from the command prompt as far as I know.
0
Chris DentPowerShell DeveloperCommented:

Besides, you have way too much variety in Operating Systems to reliably change things using scripts.

If you do use the DNS Change script I recommend you run it centrally and add logging options so you can see where it's been successful...
0
georgecooldudeAuthor Commented:
Oh yeah I forgot about the plain text password thing with the standard scripts.

Now I think of it I will also have to do something with the user profiles. For instance on my XP Machine when i log onto my windows 2003 server I've a new profile locally created on my machine. As such things like my outlook.pst aren't there. Nor my desktop icons/settings.

Now I thinking if I create scripts to move all this aswell its going to get very complicated. I seem to solve 1 problem and up comes another...
0
Chris DentPowerShell DeveloperCommented:

You'd be better off visiting the PC...

Then you can do the DNS Changes, any Domain Name changes, log in as the user (to create a blank profile) and finally copy their own user profile over.

It might take time, but you'll know that it's working...
0
georgecooldudeAuthor Commented:
Chris this is a good point.

I have had a talk with a few people.

We thought we could create a few .bat scripts of somesort that we can run on a floppy on each machine we visit.

Is there a dos compatiable way i could remove DNS servers and add in a new one?
0
Chris DentPowerShell DeveloperCommented:

You can run the vbscript from the command line.

Just set everything you want to set in the file itself, the use:

cscript dnsconfig.vbs

Or use that line in a batch file...

The script at the top simply overwrites the existing list of servers with a new one. I haven't tested it on Windows 9x though, haven't had one of those installed for quite some time ;)

The Profile copy is slightly (not very though) tricky since it locks the NTUser.dat file until the PC reboots (and you have to log on once to create the blank profile to start with), you might be able to get away with skipping that file though.
0
georgecooldudeAuthor Commented:
ah ok thanks!

I was wondering how to run vb scrtip from a batch file
0
Chris DentPowerShell DeveloperCommented:

cscript <script name> for Command Prompt

wscript <script name> for Windows Shell

Double Click in windows is associated with wscript.

;)
0
georgecooldudeAuthor Commented:
Cool!

I will right those down for future referrence. :-)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Windows Server 2003

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.