How to Detect Drive letter of a Flash drive from Batch Script
I saw a question on a popular forum asking How to detect drive letter of a flash drive from cmd (Command prompt).
Detecting drive letter from command prompt is possible but a bit tricky, First we have to get into Diskpart then identify the disk type and obtaining the drive letter. Scripting this can be difficult. Instead going this route Why not try a easy VBScript ?
In this tutorial We will see a vb-script which will detect the drive letter of a USB removable drive and output either on screen or on the cmd console.
‘ VBscript to detect the drive letter for a flash drive
Dim objWMIService, objItem, colItems, strComputer
Dim strDriveType, strDiskSize
On Error Resume Next
strComputer = “.”
Set objWMIService = GetObject _
(“winmgmts:\\” & strComputer & “\root\cimv2″)
Set colItems = objWMIService.ExecQuery _
(“Select * from Win32_LogicalDisk”)
For Each objItem in colItems
Select Case objItem.DriveType
Case 1 strDriveType = “Drive could not be determined.”
Case 2 strDriveType = “Removable Drive”
Case 3 strDriveType = “Local hard disk.”
Case 4 strDriveType = “Network disk.”
Case 5 strDriveType = “Compact disk (CD)”
Case 6 strDriveType = “RAM disk.”
Case Else strDriveType = “Drive type Problem.”
If objItem.DriveType =2 Then
As you can see, here we have 5 different type of drives which can be identified using this script. Those are
- Removable Drive
- Local hard disk.
- Network disk.
- Compact disk (CD)
- RAM disk.
How to use this Script to detect drive letter from CMD -
- Save it as DetectFlashDrive.vbs in a directory.
- Open CMD
- Switch to the directory where you saved this vbs
- type cscript DetectFlashDrive.vbs and hit Enter.
- Example is shown in the screenshot below
If you look closely, I have typed 2 different commands and they gave different output. First command output includes Microsoft script host logo whether 2nd does not include it. So if you have to hide the logo, add /nologo after cscript.Further, You can assign this output to a variable and later use in a batch script – To assign this output as a variable call this :[stextbox id="grey"]for /f %a in (‘cscript/nologo DetectFlashDrive.vbs’) do set drive=%a [/stextbox]
Now the USB drive’s letter is assigned to the variable ”%drive% which can be called from anywhere in your command session. To call this type “Echo %drive%.
That’s it for today, if you are a script lover, You might want to receive next tutorial via email. Simply put your email address in this box.
External References : WMI – Logical Disk Properties