我需要包含一个"否则回音没有USB检测"进入这个.bat(不添加"如果%% l NEQ 2")
for /F "usebackq tokens=1,2,3,4 " %%i in (`wmic logicaldisk get caption^,description^,drivetype 2^>NUL`) do (
if %%l equ 2 (
echo USB detect in %%i
)
)
简单来说:如果检测到USB,那么"回显OK"。但是如果它没有检测到USB,那么"回声No"并退出。感谢
解决 Tim
重要提示:
在我看来,这个脚本(由Stephan)检测驱动器要高得多
@echo off
setlocal enabledelayedexpansion
REM get removable loaded drives:
for /f %%a in ('"wmic logicaldisk where (drivetype=2 and size is not null) get caption,size 2>nul|find ":""') do set usb=!usb! %%a
REM show a overview:
if defined usb (echo removable drives found in: %usb%) else echo no removable drive found
REM show them one-by-one:
for %%a in (%usb%) do echo removable drive found in %%a
答案 0 :(得分:1)
wmic
比你想象的更有力量:
@echo off
setlocal enabledelayedexpansion
REM get removable loaded drives:
for /f %%a in ('"wmic logicaldisk where (drivetype=2 and size is not null) get caption,size 2>nul|find ":""') do set usb=!usb! %%a
REM show a overview:
if defined usb (echo removable drives found in: %usb%) else echo no removable drive found
REM show them one-by-one:
for %%a in (%usb%) do echo removable drive found in %%a
答案 1 :(得分:0)
此代码适用于我。将其保存到 test.bat 并从打开的Cmd提示符运行。它只打印磁盘相关信息,没有垃圾:
@echo off
setlocal enabledelayedexpansion
for /F "usebackq tokens=* skip=1" %%i in (`wmic logicaldisk get caption^,description^,drivetype 2^>NUL`) do (set "dsk=%%i"
if "!dsk:~-12,1!" equ "2" (echo USB disk detected in !dsk:~0,2!
) else if "!dsk:~-12,1!" gtr "2" (echo No USB disk detected in !dsk:~0,2!) )
exit /b
答案 2 :(得分:0)
您的问题是在ELSE
声明中添加了IF
条款。我建议在两个右括号之间添加ELSE
。这段代码正是如此:
@echo off
for /F "usebackq tokens=1,2,3,4 " %%i in (`wmic logicaldisk get caption^,description^,drivetype 2^>NUL`) do (
if %%l equ 2 (echo USB detect in %%i) ELSE (echo No USB Detect)
)
这是我的输出没有插入USB驱动器:
C:\Users\tim\Documents\Scripting Tools>usbdetect.bat
No USB Detect
No USB Detect
No USB Detect
这是插入了thumbdrive的输出:
C:\Users\tim\Documents\Scripting Tools>usbdetect.bat
No USB Detect
No USB Detect
USB detect in D:
No USB Detect
以下是我使用的WMIC命令的结果:
C:\Users\tim\Documents\Scripting Tools>wmic logicaldisk get caption,description,drivetype
Caption Description DriveType
C: Local Fixed Disk 3
D: Removable Disk 2
您可能会注意到它没有USB检测3次。这是正确的,因为您构造的FOR循环遍历每行输出。 WMIC使用标题(Caption,Description和DriveType)分配一行,每个驱动器一行(而C:不是DriveType 2),然后是一个空行。
你的最后一行,In simple words: if USB detected, then "echo OK". But if it does not detect the USB, then "echo No" and exit.
似乎暗示你只需要一个简单的已安装/未安装,而不是来自WMIC查询的每行输出的是/否。如果是这种情况,您就不需要(或想要)ELSE
。试试这个:
@echo off
for /F "usebackq tokens=1,2,3,4 " %%i in (`wmic logicaldisk get caption^,description^,drivetype 2^>NUL`) do (
if %%l equ 2 (
echo USB detect in %%i
goto RestOfBatch
)
)
echo USB not detected
:RestOfBatch
没有插入USB驱动器:
C:\Users\tim\Documents\Scripting Tools>usbdetect.bat
USB not detected
插入USB驱动器:
C:\Users\tim\Documents\Scripting Tools>usbdetect.bat
USB detect in D:
如果这些都不能产生预期结果,请更清楚地定义您的问题。 http://ss64.com/nt/有一个完整的批处理命令列表及其语法。您还可以在命令末尾添加/?
以获取示例。 EG:IF /?