How can I detect the drive letter of a booted USB drive from script?

﹥>﹥吖頭↗ 提交于 2019-12-05 11:49:10

This VBScript will show a message for each removable drive (letter:description), could be easily modified to search for a particular drive and return the letter.

 
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colDisks = objWMIService.ExecQuery("Select * from Win32_LogicalDisk where MediaType = 11")

For Each objDisk in colDisks
    Wscript.Echo objDisk.DeviceID & objDisk.Description
Next

Don't know if that helps at all.

It's a less generic solution than the others mentioned here, but there appears to be a specific way to determine which underlying volume a "RAM-drive-booted" Windows PE OS was booted from. From the documentation on Windows PE in the Windows Advanced Installation Kit:

If you are not booting Windows Deployment Services, the best way to determine where Windows PE booted from is to first check for PEBootRamdiskSourceDrive registry key. If it is not present, scan the drives of the correct PEBootType and look for some kind of tag file that identifies the boot drive.

(The registry value in question sits under HKLM\SYSTEM\CurrentControlSet\Control.)

Here's a non-optimal solution. In this case, the UFD has to have a specific name, which is passed to the script which searches every possible drive letter for a match. It's probably not practical to rely on the flash drives all having the same name.

Still hoping someone pops by with a better answer!

setlocal

:: Initial variables
set TMPFILE=%~dp0getdrive.tmp
set driveletters=abcdefghijklmnopqrstuvwxyz
set MatchLabel_res=

for /L %%g in (2,1,25) do call :MatchLabel %%g %*

if not "%MatchLabel_res%"=="" echo %MatchLabel_res%

goto :END

:: Function to match a label with a drive letter. 
::
:: The first parameter is an integer from 1..26 that needs to be 
:: converted in a letter. It is easier looping on a number
:: than looping on letters.
::
:: The second parameter is the volume name passed-on to the script
:MatchLabel

:: result already found, just do nothing 
:: (necessary because there is no break for for loops)
if not "%MatchLabel_res%"=="" goto :eof

:: get the proper drive letter
call set dl=%%driveletters:~%1,1%%

:: strip-off the " in the volume name to be able to add them again further
set volname=%2
set volname=%volname:"=%

:: get the volume information on that disk
vol %dl%: > "%TMPFILE%" 2>&1

:: Drive/Volume does not exist, just quit
if not "%ERRORLEVEL%"=="0" goto :eof

set found=0
for /F "usebackq tokens=3 delims=:" %%g in (`find /C /I "%volname%" "%TMPFILE%"`) do set found=%%g

:: trick to stip any whitespaces
set /A found=%found% + 0


if not "%found%"=="0" set MatchLabel_res=%dl%:
goto :eof

:END

if exist "%TMPFILE%" del "%TMPFILE%"
endlocal
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!