Your question was adding an ELSE
clause to your IF
statement. I recommended adding ELSE
between your two close parenthesis. This code does exactly that:
@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)
)
This is my output with no USB drives plugged in:
C:\Users\tim\Documents\Scripting Tools>usbdetect.bat
No USB Detect
No USB Detect
No USB Detect
This is my output with a thumbdrive plugged in:
C:\Users\tim\Documents\Scripting Tools>usbdetect.bat
No USB Detect
No USB Detect
USB detect in D:
No USB Detect
Here is my result of the WMIC command you used:
C:\Users\tim\Documents\Scripting Tools>wmic logicaldisk get caption,description,drivetype
Caption Description DriveType
C: Local Fixed Disk 3
D: Removable Disk 2
You might notice it echos No USB Detect 3 times. This is correct because the FOR loop you have constructed loops through each line of output. WMIC outouts one line with the headers (Caption, Description, and DriveType), a line for each drive (and C: is not DriveType 2), and then a blank line.
Your last line, In simple words: if USB detected, then "echo OK". But if it does not detect the USB, then "echo No" and exit.
Seems to imply that you only want a simple Installed/Not Installed, not a yes/no for each line of output from your WMIC query. If that is the case, you don't need (or want) an ELSE
. Try this instead:
@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
Without a usb drive plugged in:
C:\Users\tim\Documents\Scripting Tools>usbdetect.bat
USB not detected
And with a usb drive plugged in:
C:\Users\tim\Documents\Scripting Tools>usbdetect.bat
USB detect in D:
If neither of these produce the desired result, please define your issue more clearly. http://ss64.com/nt/ has a comprehensive list of batch commands and their syntax. You can also add /?
to the end of a command to get examples. EG: IF /?