Marcus
Marcus

Reputation: 13

how to access a usb drive using its label and navigate with CMD

I would like to know if it's possible to access a usb drive using its label, for example I can navigate to the drive with PowerShell but I would like to know how to do something similar to this in CMD

$usbPath = Get-WMIObject Win32_Volume | ? { $_.Label -eq 'volumelabel' } | select name ; cd $usbPath.name 

Upvotes: 1

Views: 2459

Answers (2)

Compo
Compo

Reputation: 38708

The simplest, and much quicker that loading , method would be to use the VOL command

For %G In (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)Do @Vol %G: 2>NUL|%__AppDir__%find.exe /I "volumelabel">NUL&&CD /D %G:

@For %%G In (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
) Do @Vol %%G: 2>NUL | %__AppDir__%find.exe /I "volumelabel" >NUL && CD /D %%G:

Instead of just checking every possible drive letter, you could reduce that to only mounted drive letters by using MountVol:

From :

For /F "Delims=\ " %G In ('"%__AppDir__%mountvol.exe 2>NUL|%__AppDir__%find.exe ":\""') Do @Vol %G 2>NUL|%__AppDir__%find.exe /I "volumelabel">NUL&&CD /D %G

From a

@For /F "Delims=\ " %%G In ('"%__AppDir__%mountvol.exe 2>NUL|%__AppDir__%find.exe ":\""'
) Do @Vol %%G 2>NUL | %__AppDir__%find.exe /I "volumelabel" >NUL && CD /D %%G

If you still wanted to use and you have sufficient privileges to use `Path Win32_Volume`, *(or its alias `Volume`)*, with it then…

From :

For /F "Skip=1Tokens=2" %G In ('%__AppDir__%wbem\WMIC.exe Volume Where "Label='volumelabel'" Get DriveLetter^,Name 2^>NUL')Do @CD /D %G

And from a :

@For /F "Skip=1 Tokens=2" %%G In (
    '%__AppDir__%wbem\WMIC.exe Volume Where "Label='volumelabel'" Get DriveLetter^,Name 2^>NUL'
) Do @CD /D %%G

Otherwise you could use Path Win32_LogicalDisk, (or its alias LogicalDisk) instead…

From :

For /F "Skip=1Tokens=2" %G In ('%__AppDir__%wbem\WMIC.exe LogicalDisk Where "VolumeName='volumelabel'" Get DeviceID^,Name 2^>NUL')Do @CD /D %G

And from a :

@For /F "Skip=1 Tokens=2" %%G In (
    '%__AppDir__%wbem\WMIC.exe LogicalDisk Where "VolumeName='volumelabel'" Get DeviceID^,Name 2^>NUL'
) Do @CD /D %%G

Upvotes: 2

Nico Nekoru
Nico Nekoru

Reputation: 3112

You can use wmic logicaldisk get name, volumename to see all of the connected drives and their drive letters and then use | <name> to find your specified drive where is the label for your drive. So in all you would do

for /f %%i in ('"wmic logicaldisk get name, volumename | find "DRIVENAME" "') do (set Driveletter=%%i) 
cd %Driveletter%

Upvotes: 1

Related Questions