0

I want to write a batch file such that when I run it in cmd, it sets a new variable equal to the drive letter of my usb flash drive (if, of course, it's the only storage device of that type). Assume ,for now, that I don't care whether it has colon appended to it or not.

This is what I tried while having a functioning Integral USB connected to my laptop:

@echo off
for /F "tokens=1,2,3,4,5" %%A IN ('wmic logicaldisk get description') DO ( 
    if %%A=="Removable Disk" (
        @echo wmic logicaldisk get caption
    )else (
        @echo no luck!
    )
)

This was the output:

no luck!
no luck!
no luck!
no luck!
no luck!
no luck!

Can anyone point out some of the obvious errors in the script?

Also this is the result of the wmic commands being ran from cmd:

C:\Users\Dziugas\Desktop>wmic logicaldisk get caption,description
Caption  Description
C:       Local Fixed Disk
D:       CD-ROM Disc
E:       CD-ROM Disc
F:       Removable Disk
0

You're close. You want to skip the first line. You want to get both the description and the device id at the same time (comma is reserved so you have to esacpe it with a caret), and since the output has spaces in it, you have to include multiple outputs in the if and put it in quotes. Here is a sample that gets the last removable disk and the last local fixed disk. Getting the first of each would be trickier, but it sounds like you're only going to have one anyway. You could use this however you would like, eg. piping into another process.

@echo off 
REM setlocal keeps the variables from escaping the batch file (which I assume you want?)
setlocal
for /F "skip=1 tokens=1-10" %%A IN ('wmic logicaldisk get description^, deviceid') DO ( 
    REM echo %%A %%B %%C %%D %%E %%F %%G
    if "%%A %%B"=="Removable Disk" (
        set LastRemovableDisk=%%C
    )
    if "%%A %%B %%C"=="Local Fixed Disk" (
        set LastFixedDisk=%%D
    )
)

REM This part is just to demonstrate the output
echo %LastRemovableDisk%
echo %LastFixedDisk%
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.