Detecting Removable drive letter in CMD

僤鯓⒐⒋嵵緔 提交于 2019-12-06 13:52:08

You need to double the % sign used to mark a FOR loop control variable in a batch script (.bat or .cmd), i.e. use %%i instead of %i used in pure CLI.

However, there is another possible approach how-to parse wmic output. See also Dave Benham's WMIC and FOR /F: A fix for the trailing <CR> problem

@echo OFF
SETLOCAL enableextensions
set "USBCounter=0"
for /F "tokens=2 delims==" %%G in ('
    WMIC logicaldisk where "DriveType=2" get DeviceID /value 2^>NUL ^| find "="
') do for /F "tokens=*" %%i in ("%%G") do (
    set /A "USBCounter+=1"
    echo %%i
    rem your stuff here
)
echo USBCounter=%USBCounter%
rem more your stuff here
ENDLOCAL
goto :eof

Here the for loops are

  • %%G to retrieve the DeviceID value;
  • %%i to remove the ending carriage return in the value returned: wmic behaviour: each output line ends with 0x0D0D0A (CR+CR+LF) instead of common 0x0D0A (CR+LF).

One could use Caption or Name instead of DeviceID:

==>WMIC logicaldisk where "DriveType=2" get /value | find ":"
Caption=F:
DeviceID=F:
Name=F:

Note there could be no or more disks present having DriveType=2:

==>WMIC logicaldisk where "DriveType=2" get /value | find ":"
No Instance(s) Available.

==>WMIC logicaldisk where "DriveType=2" list brief
DeviceID  DriveType  FreeSpace   ProviderName  Size        VolumeName
F:        2          2625454080                3918512128  HOMER
G:        2          999600128                 1029734400  LOEWE

Script output for no, then one and then two USB drive(s), respectively:

==>D:\bat\SO\31356732.bat
USBCounter=0

==>D:\bat\SO\31356732.bat
F:
USBCounter=1

==>D:\bat\SO\31356732.bat
F:
G:
USBCounter=2

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