I'm trying to refer to a drive whose letter may change. I'd like to refer to it by its label (e.g., MyLabel (v:) within a Batch File. It can be referred to by V:\ . I'd like to refer to it by MyLabel.
(This was posted on Experts Echange for a month with no answer. Let's see how fast SO answers it )
When you connect a new drive to your PC, Windows automatically assigns the next available letter after C, which is normally used for your system drive.
In computer data storage, drive letter assignment is the process of assigning alphabetical identifiers to volumes. Unlike the concept of UNIX mount points, where volumes are named and located arbitrarily in a single hierarchical namespace, drive letter assignment allows multiple highest-level namespaces.
Drive letters are normally assigned by Windows at installation with the OS partition as C:, every other hard drive and partition in somewhat physical order, CD/DVD/BR drives installed, then any other partitions/hard drives/removable drives added after installation.
Alternatively referred to as a device letter, a drive letter is a single alphabetic character A through Z that is assigned to a physical computer drive or drive partition. For example, a computer with a 3 1/2" floppy diskette drive has a drive letter of A: assigned to the drive.
The previous answers seem either overly complicated, and/or not particularly suited to a batch file.
This simple one liner should place the desired drive letter in variable myDrive. Obviously change "My Label" to your actual label.
for /f %%D in ('wmic volume get DriveLetter^, Label ^| find "My Label"') do set myDrive=%%D
If run from the command line (not in a batch file), then %%D must be changed to %D in both places.
Once the variable is set, you can refer to the drive using %myDrive%
. For example
dir %myDrive%\someFolder
This bat file will give you the drive letter from a drive label:
Option Explicit
Dim num, args, objWMIService, objItem, colItems
set args = WScript.Arguments
num = args.Count
if num <> 1 then
WScript.Echo "Usage: CScript DriveFromLabel.vbs <label>"
WScript.Quit 1
end if
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk")
For Each objItem in colItems
If strcomp(objItem.VolumeName, args.Item(0), 1) = 0 Then
Wscript.Echo objItem.Name
End If
Next
WScript.Quit 0
Run it as:
cscript /nologo DriveFromLabel.vbs label
You can use the WMI query language for that. Take a look at http://msdn.microsoft.com/en-us/library/aa394592(VS.85).aspx for examples. The information you are looking for is available e.g. through the property VolumeName of the Win32_LogicalDisk class, http://msdn.microsoft.com/en-us/library/aa394173(VS.85).aspx
SELECT * FROM Win32_LogicalDisk WHERE VolumeName="MyLabel"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With