Windows Logon Script – To Map the First Available Drive Letter

Introduction to Mapping the First Available Drive Letter

This page builds on the simple MapNetworkDrive script.  Consequently, I advise you to take a refresher on my Map Net Drv Simple script, before attempting this example.  The key point of the advanced script on this page is that it checks to see if the drive is already available.  Should the letter be in use, then VBScript tries the next letter in sequence, which you can define.  Normally, if you execute a MapNetworkDrive script for a second time, the script would fail.  However, this script has error-correcting logic and if the drive is already mapped, then it tries an alternative letter.

You could view this script as a bit of fun, or as a chance to experiment with additional scripting techniques such as EnumNetworkDrives, looping and if .. then … else.. endif commands.

Topics for Mapping the First Available Drive Letter

 ♦

Mission – To Map to the First Available Drive Letter

Have you ever experienced the problem where your script attempts to map a network drive, but unfortunately the drive letter is already in use?  Well my script overcomes this ‘in use’ error.  What the code does is enumerate the mapped drives, as a result it can detect drive letters that are already in use.  Not only does it avoid an error, but it also loops to the next letter in your sequence.

One possible scenario is that you want to map a network drive, but you do not really mind which letter the script chooses.  Therefore, you provide a list of alternative letters and the script maps the first available drive letter.

Scripts constantly remind me that they merely automate what we humans can do manually.  Where scripts are at their best, is when you have a repetitive sequence of tasks.  The trick is to choose the best type of loop for the job, for example For…Next, or Do… Until.  The trap is omitting essential commands inside the loop, or else leave vital sequences outside the loop.  What makes this script complicated, is that it has not one loop, but two loops, one inside the other.

Example 1  – To Map to the First Available Drive Letter

The question my script keeps asking is this: ‘Does this particular drive letter exist?’  If the answer is false, then the drive letter is available, so code choose to map that particular letter.  Job done.  However, if that particular letter is already in use, then the loop tests the next letter in the sequence and repeats my DriveExists test.

Instead of my normal tactic of building the script in stages, I have decided to present you with the full script in one complete example.  One reason for this unusual approach is that it’s difficult to separate the two loops.  As there are no preparation scripts on this page I strongly recommend you review both the MapNetworkDrive and especially, the EnumNetworkDrives scripts.

Instructions for mapping to the first available drive letter

  1. Create your network share.  Edit the variable strRemotePath on Line 14.
  2. Edit your drive letters in strAlpha = "BJMRU"  on line 16.
  3. Copy and paste the script below into notepad or get a script editor such as OnScript (free download).
  4. Save the file with a .vbs extension e.g. FirstLetter .vbs.
  5. Double click the script, read the message box, check drive letters in Explorer.  Press F5 to refresh.

‘ FirstLetter.vbs Windows Logon Script
‘ VBScript to map the first available drive letter
‘ Author Guy Thomas https://computerperformance.co.uk/
‘ Version 3.7 – September 2010
‘ ——————————————————‘
Option Explicit
Dim strDriveLetter, strRemotePath
Dim objNetwork, objShell
Dim CheckDrive, DriveExists, intDrive
Dim strAlpha, strExtract, intAlpha, intCount

‘ The section sets the variables
‘ N.B. Change strRemotePath
strRemotePath = "\\grand\Home"
strDriveLetter = "B:"
strAlpha = "BJMRU"
intAlpha = 0
intCount = 0
err.number= vbEmpty

‘ This sections creates two objects:
‘ objShell and objNetwork and then counts the drives
Set objShell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
Set CheckDrive = objNetwork.EnumNetworkDrives()

‘ This section operates the For … Next loop
‘ See how it compares the enumerated drive letters
‘ With strDriveLetter
On Error Resume Next
DriveExists = False
‘ Sets the Outer loop to check for 5 letters in strAlpha
For intCount = 1 To 5
   DriveExists = False
  
   ‘ CheckDrive compares each Enumerated network drive
   ‘ with the proposed drive letter held by strDriveLetter
      For intDrive = 0 To CheckDrive.Count – 1 Step 2
        If CheckDrive.Item(intDrive) = strDriveLetter _
        Then DriveExists = True
      Next
  intAlpha = intAlpha + 1

  ‘  Logic section if strDriveLetter does not = DriveExist
  ‘ Then go ahead and map the drive

  Wscript.Echo strDriveLetter & " exists: " & DriveExists
  If DriveExists = False Then objNetwork.MapNetworkDrive _
  strDriveLetter, strRemotePath
  call ShowExplorer ‘ Extra code to take you to the mapped drive
  ‘ Appends a colon to drive letter. 1 means number of letters
  strDriveLetter = Mid(strAlpha, intAlpha,1) & ":"
 
  ‘ If the DriveExists, then it is necessary to
  ‘ reset the variable from true –> false for next test loop
  If DriveExists = True Then DriveExists = False

Next

WScript.Echo "Out of drive letters. Last letter " & strDriveLetter

WScript.Quit(1)

Sub ShowExplorer()
If DriveExists = False Then objShell.run _
("Explorer" & " " & strDriveLetter & "\" )
If DriveExists = False Then WScript.Quit(0)
End Sub

‘ Guy’s First Available Letter Script Example ends here

Learning Points for Mapping to the First Available Drive Letter

Note 1:  Trace the outer loop, focussing on strDriveLetter.  For a given letter, ask, ‘Does this letter = any of the existing mapped network drives?’  If yes, then loop and get another letter from strAlpha.  If no then success.  The script maps that letter because it is free and there is no danger of a conflict.

Note 2:  The inner loop is where the script compares strDriveLetter with each drive exposed by the EnumNetworkDrives function.

Note 3:  You may prefer to choose a different selection of drive letters for strAlpha.  Surprisingly, the list does not have to be in alphabetical order.  However, you should not include the letters of local hard drives.

Note 4:  Observe the importance of EnumNetworkDrives, and check the plural spelling of this method.

Note 5:  The subroutine ShowExplorer() at the end of the script is not strictly necessary, it merely opens the explorer to confirm that the mapped drive now exists.

Challenges :  If you take up my theme of developing your own scripts; experiment with different variable names, amend my WScript.Echo messages, add error correcting code, choose different letters to map.

Guy Recommends SolarWinds’ Free Network MonitorSolarwinds Network Device Monitor

Thus utility makes it easy to check the health of a router or firewall.  Check the real-time performance, and availability statistics, for any device on your network.  Get started with an extensive collection of "out-of-the-box" monitors for popular network devices. Give Network Monitor a whirl – it’s free. Download your free Network Device Monitor

If you need more comprehensive network analysis software:
Download a free trial of NPM (Network Performance Monitor)

Example 2 – Variation which does not launch Windows Explorer

‘ FirstLetter.vbs Windows Logon Script
‘ VBScript to map the first available drive letter
‘ Author Guy Thomas https://computerperformance.co.uk/
‘ Version 3.8 – November 2007
‘ Variation which does not launch Explorer
‘ ——————————————————‘
Option Explicit
Dim strDriveLetter, strRemotePath
Dim objNetwork, objShell
Dim CheckDrive, DriveExists, intDrive
Dim strAlpha, strExtract, intAlpha, intCount

‘ The section sets the variables
‘ N.B. Change strRemotePath
strRemotePath = "\\grand\df4"
strDriveLetter = "Y:"
strAlpha = "YJMRU"
intAlpha = 0
intCount = 0
err.number= vbEmpty

‘ This sections creates two objects:
‘ objShell and objNetwork and then counts the drives
Set objShell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
Set CheckDrive = objNetwork.EnumNetworkDrives()

‘ This section operates the For … Next loop
‘ See how it compares the enumerated drive letters
‘ With strDriveLetter
On Error Resume Next
DriveExists = False
‘ Sets the Outer loop to check for 5 letters in strAlpha
For intCount = 1 To 5
DriveExists = False

‘ CheckDrive compares each Enumerated network drive
‘ with the proposed drive letter held by strDriveLetter
For intDrive = 0 To CheckDrive.Count – 1 Step 2
If CheckDrive.Item(intDrive) = strDriveLetter _
Then DriveExists = True
intCount = 5
Next
intAlpha = intAlpha + 1

‘ Logic section if strDriveLetter does not = DriveExist
‘ Then go ahead and map the drive

If DriveExists = False Then objNetwork.MapNetworkDrive _
strDriveLetter, strRemotePath
If DriveExists = False Then WScript.Quit(0)

‘ Appends a colon to drive letter. 1 means number of letters
strDriveLetter = Mid(strAlpha, intAlpha,1) & ":"

‘ If the DriveExists, then it is necessary to
‘ reset the variable from true –> false for next test loop
If DriveExists = True Then DriveExists = False

Next

WScript.Quit(1)

‘ Guy’s First Available Letter Script Example ends here

See how to perform similar tasks in PowerShell

Summary of Mapping the First Available Drive Letter

It is annoying if a map network drive script fails simply because the drive has already been mapped.  This script loops through a sequence of letters until it finds a free drive letter.  Note how it employs only MapNetworkDrive, but also EnumNetworkDrives.

 

Download my Logon Script eBook for only $6.25

Logon ScriptThe extra features you get in your eBook include, more pages full of detailed examples.  Also, ten ‘how to…’ sections, with screen shots showing which menus to use.  Go for Guy’s eBook – and get a printable version with copy enabled and no expiry date.

  Jumbo Script 7 Package

If you like this page then please share it with your friends

 


See more logon scripts examples

Logon Script Home   •EnumNetworkDrives   • Map Network Drive Group   • Free Import CSV Tool

Map Network Drive Script   • Vbscript Map Network Drive Username   • Map Multiple Network Drives

ObjNetwork.MapNetworkDrive   • Disconnect Network Drives   • Logon script group policy