Search code examples
batch-filecmdusbdrive-letter

batch file detects drive letter of the USB flash drive it's on then opens cmd prompt


I would like to put a batch file on a USB flash drive that I can just plug in and run the batch. I would like the batch to detect what drive letter has been assigned to the USB flash drive, then open a command prompt and change the directory to the drive letter of the USB flash drive in which then type a command string into the cmd prompt and enter a CR to execute the command.

I don't even know where to begin. I've searched for cmd batch related topics but haven't had any luck on actually detecting the drive letter in which a USB flash drive has been assigned after plugging it into a PC.

Any help would be much appreciated. Thank you.


Solution

  • This will tell you the drive letter assigned

    @echo off
    setlocal   
    set wmi='wmic logicaldisk where "volumeserialnumber='32A78F3B'" get caption'
        for /f "skip=1 delims=" %%A in (%wmi%) do (
            for /f "tokens=1 delims=:" %%B in ("%%A") do (set drive=%%B)
        )
    echo %drive%
    

    To get the volume serial number, type

    vol [drive letter of flashdrive:]
    

    But all of that isn't necessary if you are running the batch file from the USB drive. Just insert

    cd /d %~dp0 
    

    at the top of your batch file and it will change to the directory the batch file is run from. From there just add your code.

    Do you want the batch file to automatically run when you insert the USB drive? Your question isn't clear on that point.