你需要double the %
用于标记一个的标志FOR
批处理脚本中的循环控制变量(.bat
or .cmd
),即使用%%i
代替%i
在纯 CLI 中使用。
然而,还有另一种可能的方法如何解析wmic
输出。
另请参阅戴夫·贝纳姆的WMIC and FOR /F: 修复了尾随的问题<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
这里的for
循环是
-
%%G
检索DeviceID
value;
-
%%i
删除结尾回车在返回值中:wmic
行为:每个输出行以0x0D0D0A
(CR+CR+LF
)而不是常见的0x0D0A
(CR+LF
).
一个可以使用Caption
or Name
代替DeviceID
:
==>WMIC logicaldisk where "DriveType=2" get /value | find ":"
Caption=F:
DeviceID=F:
Name=F:
注意可能有no or more磁盘存在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进而twoUSB 驱动器分别:
==>D:\bat\SO\31356732.bat
USBCounter=0
==>D:\bat\SO\31356732.bat
F:
USBCounter=1
==>D:\bat\SO\31356732.bat
F:
G:
USBCounter=2
==>