0

I have a PC in which I insert a USB Drive and execute a batch script, but the USB Drive interacts with the computer, so I need to know in which Drive Letter it is mounted.

I tried this

    for /f "tokens=2,3 delims= " %%A in ('WMIC logicaldisk where "DriveType=2" get /value | find "Caption="') do (
set drive=%%A
)

But I get an error stating Did not expect %%A at this moment.

I know this works

@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 %%i is a USB drive.
)
)

But it implies having to save it in a .bat file, and I don't want to do that.

Ideally, what I want to do is to be able to switch to the USB Drive without needing to launch it from a .bat file, so this command should allow me to get the Drive Letter. Afterwards, the script continues.

Hamperfait
  • 465
  • 1
  • 6
  • 18
  • 1
    In `cmd` you must use `%A` rather than `%%A`. And you must escape the pipe like `^|` in order not to be recognised by the hosting `cmd` instance that executes the `for /F` loop (this is also true when using similar code in a batch file)... – aschipfl Dec 23 '19 at 12:29
  • Where is the batch script, on the PC? or on the USB device? – Compo Dec 23 '19 at 12:51
  • @Compo, the batch script is on the USB device, but I need to get somehow the drive on which it is mounted in one single command, without executing the script beforehand. – Hamperfait Dec 23 '19 at 13:41
  • I think your question is confusing. How are you running the command which invokes the batch script on the USB device? Please explain the actual task, from the point that you insert/mount the USB device. – Compo Dec 23 '19 at 14:33
  • This may be of interest. It waits for a USB drive to be inserted then copies the contents somewhere. https://stackoverflow.com/questions/59442263/how-can-i-run-a-bat-file-saved-on-my-system-automatically-whenever-any-pendrive/59442307#59442307 –  Dec 23 '19 at 16:40

1 Answers1

0

Thanks to the @aschipfl I managed to find out the right command:

for /F "usebackq tokens=1,2,3,4 " %i in (`WMIC logicaldisk where "DriveType=2" get /value ^| find "Caption="`) do (set drive=%i)
set drive=%drive:~8,9%

And now %drive% is the letter in which the drive is mounted. If there are more than one mounted letters, it will be the last one.

Hamperfait
  • 465
  • 1
  • 6
  • 18
  • This doesn't make sense in relation to a real world task. The first command line attempts sets a variable within the running cmd.exe instance. The second command line modifies the variable value held in the local variable. As soon as the cmd.exe instance has closed, the variable will no longer exist or reference that previous location. A more efficient way of doing this is to use a known label for the device, or to use a known uniquely named file or directory upon that device. – Compo Dec 23 '19 at 14:44
  • Also, what happens if there is more than one drive of type 2? – lit Dec 23 '19 at 17:11