Tuesday, September 8, 2009

How to map network drive using VBScript

Some time it is required to map a network drive using vbscript.
Today I will demonstate how to connet and then disconnect from a network drive.

In order to connect to a network drive, we need following data/information:

1. HomeServer Location: Actual path of the drive. In our example it is
"\\125.99.218.158\Data"

2. Name of the drive you wish to give: Let us say Z:

3. UserId/Password using which we will connect the map drive. If userid is same as logged in user then it is not required.

We will create an object of WScript.Network and call its method MapNetworkDrive

Here is the code:

Option Explicit
Dim strUser, strPassword, strDriveLetter, strHomeServer, strProfile
Dim objNetwork
Set objNetwork = CreateObject("WScript.Network")

strDriveLetter = "Z:"
strHomeServer = "\\125.99.218.158\Data"
strProfile = "False" ' Mapping (not) stored in user Profile
strUser = "USERID"
strPassword = "PASSWORD"

objNetwork.MapNetworkDrive strDriveLetter,strHomeServer,strProfile,strUser,strPassword

WScript.Quit


So the above code is creating an object of Wscript.Network and calling method MapNetworkDrive by passwing parameters like drive letter, hom server, userid and password.
There is one more parameter that is strProfile. If set true, it will store the drive info in user profile and it will connect automatically next time when user logs in.

3 comments:

sluice said...

Is it possible to get the script to ask for a password when connecting to a foreign domain, rather than having to put the password in clear in the script?

Varun Sharma said...

Yes it is possible.
Instead of storing the password in the file , you can ask an user to enter the password

strPassword =Inputbox("Enter the Network password")

That will meet your requirement.

Albert Andrada said...

Really Nice Information,Thank You Very Much For Sharing.
Web Development Company