I'm trying to find the next available drive letter for mapping a network path from within a Windows Script Host (WSH) script. I know that I can query Windows Management Instrumentation (WMI) to get the already-used drive letters, but I'd like to find an easier method. What's the best way to find the next free drive letter?
You can use the Scripting Runtime Library's FileSystemObject object. This object is faster and easier to use than WMI and is certain to be available if WSH is installed because WSH and the Scripting Runtime Library are part of the same Microsoft Windows Script (WS) download. You can also restrict the range of letters you're checking. Although most Windows OSs let you use letters A, B, and C for mapping network paths, some applications don't let you use these letters. To minimize potential problems, checking drive letters D through Z is best.
The NextFreeDrive function, which Listing 1 shows, uses the FileSystemObject object to check the availability of drive letters D through Z. This function uses the character codes for the first and last letters of the range as the limits of a For...Next statement. To check a drive's availability, the function calls the FileSystemObject object's DriveExists method, which provides a True value if the drive exists and a False value if it doesn't exist. When DriveExists returns the first False value, the function assigns the letter to the NextFreeDrive variable, then quits. You can then use that variable's value to map a network path.