How-to: Create a robust and persistent Drive Mapping [MapDrivePersistent.vbs]

VBScript to Map a Drive letter to a network file share (persistent)

This script is designed to maximise the speed of login, so if a drive already has the correct persistent connection it will be left alone. This is a good approach for machines that are running a recent version of Windows and which are always connected to the domain.

For each drive letter there are several possible states, that may have to be dealt with by the script:
- Remembered (persistent connection) / Not Remembered
- Already Connected / Connected to the wrong network share / Not Connected.

If a drive does have to be re-connected this script will attempt to remove any 'remembered' connections, including those to a file share that no longer exists or which is off-line.

Option Explicit
Function MapDrivePersistent(strDrive,strPath)
   ' strDrive = Drive letter - e.g. "x:"
   ' strPath = Path to server/share - e.g. "\\server\share"
   ' Returns a boolean (True or False)

   Dim objNetwork, objDrives, blnFound, objReg, i
   Dim strLocalDrive, strRemoteShare, strRemembered, strMessage
   Const HKCU = &H80000001

   ' Check syntax of parameters passed
   If Right(strDrive, 1) <> ":" OR Left(strPath, 2) <> "\\" Then
      WScript.echo "Usage: MapDrivePersistent.vbs ""X:"" ""\\server\share"" //NoLogo"
     WScript.Quit(1)
   End If

   Err.clear
   MapDrivePersistent = False

   Set objNetwork = WScript.CreateObject("WScript.Network")

   'Step 1: Get the current drives
   Set objDrives = objNetwork.EnumNetworkDrives
   If Err.Number <> 0 Then
        'Code here for error logging
        Err.Clear
        MapDrivePersistent = False
        Exit Function 
   End If

   WScript.echo "   Connecting drive letter: " + strDrive + " to " + strPath
    
   'Step 2: Compare drive letters to the one requested
   blnFound = False
   For i = 0 To objDrives.Count - 1 Step 2
        If UCase(strDrive) = UCase(objDrives.Item(i)) Then
            blnFound = True
            'Drive letter was found.  Now see if the network share on it is the same as requested
            If UCase(strPath) = UCase(objDrives.Item(i+1)) Then
                'Correct mapping on the drive
                MapDrivePersistent = True
            Else
                'Wrong mapping on drive.  Disconnect and remap
                WScript.Echo "--"
                objNetwork.RemoveNetworkDrive strDrive, True, True 'Disconnect drive
                If Err.Number <> 0 Then
                    'Code here for error logging
                    Err.clear
                    MapDrivePersistent = False
                    Exit Function
                End If

                ' To completely remove the previous remembered persistent mapping
                ' we also delete the associated registry key HKCU\Network\Drive\RemotePath
                ' In theory this should be covered by bUpdateProfile=True in
                ' the RemoveNetworkDrive section above but that doesn’t always work.
                 Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
                 objReg.GetStringValue HKCU, "Network\" & Left(strDrive, 1), "RemotePath", strRemembered
                 If strRemembered <> "" Then
                   objReg.DeleteKey HKCU, "Network\" & Left(strDrive, 1)
                 End If

               ' Connect drive
               On Error Resume Next
                WScript.Echo "++"
                objNetwork.MapNetworkDrive strDrive, strPath, True 
                If Err.Number <> 0 Then
                    'Code here for error logging
                    Err.clear
                    MapDrivePersistent = False
                    Exit Function 
                End If

                MapDrivePersistent = True
                
            End If
        End If
        
    Next'Drive in the list
    
   'If blnFound is still false, the drive letter isn’t being used.  So let’s map it.
   If Not blnFound Then
        On Error Resume Next
        objNetwork.MapNetworkDrive strDrive, strPath, True
        If Err.Number <> 0 Then
            'Code here for error logging
            Err.clear
            MapDrivePersistent = False
            Exit Function 
        End If

        MapDrivePersistent = True
   End If

   WScript.Echo "   ____"
End Function

Example:

' Call the function in VBScript
' this can just be tacked onto the main script above

if not MapDrivePersistent("L:","\\Server64\Library") Then
    Wscript.Echo "   ERROR: Drive L: failed to connect!"
End If

if not MapDrivePersistent("Z:","\\Server64\groups") Then
    Wscript.Echo "   ERROR: Drive Z: failed to connect!"
End If

Then to run the whole thing from a short batch file, or from the command line:

cscript MapDrives.vbs

You are free to use or modify this script: Creative Commons 4.0 International License.

For drive mapping to work, 'File and Printer sharing' must be enabled on the remote (server) computer.

based on a script by Corey Thomas Better Drive Mapping

“You may say I’m a dreamer, but I’m not the only one. I hope someday you’ll join us. And the world will live as one” ~ John Lennon

Related VBScript commands

MapDrive - Map a Drive letter to a network file share (non-persistent).
NET USE - Manage network resources.
.MapNetworkDrive - Drive Map.
Using Group Policy Preferences to Map Drives Based on Group Membership.
NoDrives - Hide mapped drives from Windows Explorer.
Q4471218 - Mapped drive may fail to reconnect in Windows 10, version 1809 (Red X).
Equivalent PowerShell command: New-PSDrive / New-SmbMapping - Create a mapped network drive.


 
Copyright © 1999-2024 SS64.com
Some rights reserved