Visual Basic – How to map a Network Drive in runtime

To map a network drive in Visual Basic (even in VB Script) during the execution of the code (especially useful in Scheduled Tasks) we could use this strategy to be absolutely sure the the drive we're trying to establish is available with the Drive Letter we have previoulsly chosen:

Set oFSO = CreateObject("Scripting.FileSystemObject")

str1 = "{path}"
Set objNetwork = WScript.CreateObject("Wscript.Network")
If Not oFSO.DriveExists("U:") Then
objNetwork.MapNetworkDrive "U:", "\\" & str1 & "\other", , "username", "password"
Else
objNetwork.RemoveNetworkDrive "U:", bForce, bUpdateProfile
objNetwork.MapNetworkDrive "U:", "\\" & str1 & "\other", , "username", "password"
End If

The code is simple:

  1. Initialize a Scripting.FileSystemObject and a Wscript.Network object to verify and manipulate network mapping;
  2. Set a str1 variable to the path that will be mapped to a Network Drive Letter;
  3. Verify if a Network Drive Letter is already mapped and so exist in the system;
  4. If True remove the existing mapping and create a new mapping with the given {path};
  5. If False create a new mapping with the given {path};

At the end of the script you could remove the established mapping to free up resources, close connections and free the Drive Letter to, for example, let other applications to use it you have to use this code:

objNetwork.RemoveNetworkDrive "U:", bForce, bUpdateProfile

NOTE: change the U: with your drive letter.