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

感情迁移 提交于 2021-02-11 17:51:20

问题


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 

回答1:


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

cmd

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:

batch-file

@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 cmd:

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 batch-file

@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 wmi and you have sufficient privileges to use Path Win32_Volume, (or its alias Volume), with it then…

From cmd:

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 batch-file:

@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 cmd:

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 batch-file:

@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



回答2:


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%


来源:https://stackoverflow.com/questions/61738542/how-to-access-a-usb-drive-using-its-label-and-navigate-with-cmd

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!