Search code examples
windowsbatch-filecmdwmic

capture result of wmic command to variable


I am trying to write a small batch script to install an app from a thumb drive. The problem is the drive letter changes when plugged into different machines depending on the available drive letters. I have the script to run the installation but would like to add a script to the beginning that would detect the assigned drive letter of my inserted thumb drive and store it in a variable that I could then substitute in the rest of the script for the drive letter to complete the installation.

I got the command to identify the assigned drive letter of the thumb drive which works on its own.

wmic logicaldisk where volumename="StacelandFlash" get name

Result: D: (correct)

But I can't seem to assign it to a variable.

set X=wmic logicaldisk where volumename="StacelandFlash" get name
echo X

Result: X

set X=wmic logicaldisk where volumename="StacelandFlash" get name
echo %X%

Result: wmic logicaldisk where volumename="StacelandFlash" get name


Solution

  • I suppose the batch file executed is stored on the thumb drive. And this batch file is executed with a double click. Therefore all you need is:

    set "DriveLetter=%~d0"
    

    %~d0 references the drive of argument 0 which is the batch file name. Run in a command prompt window call /? for details on how to reference arguments of a batch file. %~d0 expands to D:, E:, ...