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 the 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 of going this route Why not try an 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.

[stextbox id=”grey”]

‘ DetectFlashDriveLEtter.vbs
‘ VBscript to detect the drive letter for a flash drive

Option Explicit
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.”
End Select

If objItem.DriveType =2 Then
Wscript.Echo objItem.Name
Else

End If

Next

WSCript.Quit

[/stextbox]

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.
So if I have to get the drive letter of CD ROM, I would change the drive type in below line and leave rest as it is.
[stextbox id=”grey”]

If objItem.DriveType =2 Then
[/stextbox]
How to use this Script to detect drive letter from CMD –

To usethis script to detect drive letter of flash drive from cmd, Follow below steps : –
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.

Yes! I want to be a Geek