How to map a network drive using vbscript ?

Sometime back I posted a code to disconnect a network drive using vbscript. Now here is the code to map a local drive to a network path. This again uses WScript.Network object to map the drive. We use the filesystem object to determine if the drive is already mapped. if yes, then disconnect it first and then map it to specified path. There are two functions. One will parse the arguments to make sure right number of parameters are passed to the script. Enjoy.


'FileName : mapdrive.vbs
'Purpose : To map a local drive to a network path
'Usage : cscript //nologo mapdrive.vbs
'To Debug : cscript //D //X //nologo mapdrive.vbs
'Example : cscript //nologo mapdrive.vbs i: \\myserver\data\myshare administrator mypassword
' This code creates a mapped drive to a network path.

Function mapdrive()
' ------ SCRIPT CONFIGURATION ------
strDrive = WScript.Arguments(0) ' e.g. i:
strPath = WScript.Arguments(1)
strUser = WScript.Arguments(2) ' e.g. Administrator
strPassword = WScript.Arguments(3)
boolPersistent = True ' True = Persistent ; False = Not Persistent
' ------ END CONFIGURATION ---------

set objNetwork = WScript.CreateObject("WScript.Network")
Set ObjFSO = CreateObject("Scripting.FileSystemObject")

'Check and disconnect if the drive is already mapped.
if(ObjFSO.DriveExists(strDrive)) then
objNetwork.RemoveNetworkDrive strDrive, True, True
end if

objNetwork.MapNetworkDrive strDrive, strPath, boolPersistent, _
strUser, strPassword
if(ObjFSO.DriveExists(strDrive)) then
WScript.Echo "Successfully mapped drive : " & strDrive & " to " & strPath
end if

Set ObjFSO = nothing
Set objNetwork = nothing
end function


Function parseArgs()
Dim filelen
filelen = WScript.Arguments.length
if filelen < 4 Then
WScript.Echo("Usage : cscript //nologo mapdrive.vbs ")
WScript.Echo("Example : cscript //nologo mapdrive.vbs i: \\myserver\data\myshare administrator mypassword")
WScript.Quit()
end if
mapdrive()
End function


parseArgs()

Leave a comment