Scripting VBS Windows

Find Next Available Drive Letter

Sometimes when i cam creating a script to install an application or set up a network share, I come across the problem that the user is using the drive letter for another mapping.

So I wrote a small script to display the next usable drive letter

This script is written in vbs

 
'************************************************************************
'*
'* The script finds next available drive letter
'*
'************************************************************************

OPTION EXPLICIT

'****************** Variables Declaration ******************************
Dim dict
Dim nextDrive

'****************** Objects initialization ******************************
Set dict = CreateObject("Scripting.Dictionary")

FillDrives dict

'Finding next available network drive
nextDrive = GetNextDriveLetter(dict)

'Map Network drive section
If (nextDrive = "-1") then
wscript.echo "There is no place to put the map"
Else

wscript.echo "The next available drive was: " & nextDrive

End if

'***************** Clean used objects ***********************************
Set dict = Nothing

'***************** Functions and procedures *****************************
Function GetNextDriveLetter(ByRef dict)

Dim f, drive, curDrive, Items, i

'Assign default value to the function - in case there are no drives
GetNextDriveLetter = "-1"

'Create FSO object
Set f = CreateObject("Scripting.FileSystemObject")

'Go over all mapped drives in current computer(with FSO)
'and receive into curDrive the letter of the last used letter for mapping
For Each drive in f.drives
curDrive = left(drive,1)

'Assign the dictionary value to true(the drive exists)
dict(curDrive) = true
Next

'Go over all the items in the dictionary. The first one with value "false" we return as function result
Items = dict.Items ' Get the items.
For i = 0 To dict.Count -1 ' Iterate the array.
If (Items(i) = false) Then
GetNextDriveLetter = CHR(ASC("A") + i)
Exit For
End If
Next
End Function

Sub FillDrives(ByRef dict)

Dim i

'Fill the table of available letters (A-C) with True
For i = ASC("A") to ASC("C")
dict.Add CHR(i), true
Next
'Fill the table of available letters (D-Z) with False
For i = ASC("D") to ASC("Z")
dict.Add CHR(i), false
Next
End Sub

Leave a Reply

Your email address will not be published. Required fields are marked *