Tuesday, September 8, 2009

How to disconnect a map drive using vbscript

In my previous post, I described how to connect to a network drive.
In this post, I will demonstrate how to disconnect from an existing connected network drive.

Suppose we have a drive Z: that is a network drive connected. Following is the code regarding how ti remove it.


Option Explicit
Dim WshNetwork, ShareName
Set WshNetwork = WScript.CreateObject("WScript.Network")
ShareName = "Z:"
WshNetwork.RemoveNetworkDrive ShareName, true, true
WScript.Quit


We are creating an object of WScript.Network and calling method RemoveNetworkDrive by passing the drive letter.

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.