vbScript - Get Drive Letter by Volume Label
Please see my post vbScript - The Basics for more details on vbScript.
I have all my computers partitioned with two partitions. The drive letters are C (OS and applications) and D (user data). I use Macrium Reflect to take monthly full and daily differential images of C. To backup D Ii use a script front end for robocopy. Using a script to do the backup has one major problem. The drive letter of my dedicated backup external drive may change. I find that even if I have used Drive Manager to allocate a drive letter, there is no guarantee that this letter will never change.
What I can do is assign a unique volume label. Unfortunately I cannot directly use the volume label in any type of copy command. What we need is some way to scan all mounted drives and find the drive letter for a given volume label. We can do that by accessing the
Drives collection returned by the
FileSystemObject. If you examine the properties exposed by a single instance of a drive, for example, my D drive, via the following script:
set fso = CreateObject("Scripting.FileSystemObject") set drive = fso.GetDrive("D") Wscript.Echo "AvailableSpace =", drive.AvailableSpace Wscript.Echo "DriveLetter =", drive.DriveLetter Wscript.Echo "DriveType =", drive.DriveType Wscript.Echo "FileSystem =", drive.FileSystem Wscript.Echo "FreeSpace =", drive.FreeSpace Wscript.Echo "IsReady =", drive.IsReady Wscript.Echo "Path =", drive.Path Wscript.Echo "RootFolder =", drive.RootFolder Wscript.Echo "SerialNumber =", drive.SerialNumber Wscript.Echo "ShareName =", drive.ShareName Wscript.Echo "TotalSize =", drive.TotalSize Wscript.Echo "VolumeName =", drive.VolumeName
you get this output
AvailableSpace = 716756209664 DriveLetter = D DriveType = 2 FileSystem = NTFS FreeSpace = 716756209664 IsReady = -1 Path = D: RootFolder = D:\ SerialNumber = 912945059 ShareName = TotalSize = 1856350711808 VolumeName = D-Data
By iterating through the drives collection and comparing
VolumeName for all fixed drives that are currently ready we can easily determine the drive letter and proceed with the backup (or any other operation).
You'll notice that instead of doing
set fso = CreateObject("Scripting.FileSystemObject")
and then iterating through
fso.Drives, I just used the object directly as it was created. For operations where you will use the object only once it is quite reasonable to do this.
One final note, accessing a drive's properties (other than the
IsReady state) when the drive is not ready will result in an error. You can trap this and test for it using
On Error or you can just check