Tuesday, July 10, 2012

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 passing 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.



RemoveNetworkDrive

Remove a shared network drive mapping.
Syntax
      objNetwork.RemoveNetworkDrive(strName, [bForce], [bUpdateProfile])
Key
   objNetwork : A WScript.Network object
   strName    : The mapped drive you want to remove.
 
   bForce     : Force the removal of the mapped drive (TRUE/FALSE).
 
   bUpdateProfile : Remove the mapping from the user's profile (TRUE/FALSE).
Example
   Dim objNetwork
   Set objNetwork = CreateObject("WScript.Network")
   objNetwork.MapNetworkDrive "I:", "\\print_server\hp_01","True","jdoe","jdoepassword"

   objNetwork.RemoveNetworkDrive "I:"





No comments: