batch-filecmdusbdrive-letter

Aquiring USB Drive Letters from command and use them as choice variables


I'm trying to create a batch file for backing up folders to a usb drive. In a certain point I want the batch to show a list of all avalaible USB Drives connected to the computer and then asking the user to select the drive letter of one of them to proceed.

As for the the list: I want to combine those two outputs in one line per usb drive

wmic logicaldisk where DriveType^=2 get deviceid

wmic diskdrive where mediatype^="removable media" get Caption, SerialNumber

As for the choice command: How can i use the drive letters as choices for the user to select from?


Solution

  • The following code should:

    1. Determine your USB drive letter(s).
    2. If there are none found notify you then close.
    3. If only one is found, select it automatically.
    4. If several are found, offer a selection choice.
    @Echo Off
    SetLocal EnableExtensions EnableDelayedExpansion
    Set "USBDrv="
    For /F Tokens^=2^ Delims^=^" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe
     DiskDrive Where "InterfaceType='USB'" Assoc:List
     /AssocClass:Win32_DiskDriveToDiskPartition 2^>NUL
     ^| %SystemRoot%\System32\findstr.exe "^__R"'
    ) Do For /F Tokens^=4^ Delims^=^" %%H In ('%SystemRoot%\System32\wbem\WMIC.exe
     Path Win32_LogicalDiskToPartition ^| %SystemRoot%\System32\findstr.exe /C:"%%G"
     2^>Nul') Do Set "USBDrv=!USBDrv!%%H"
    If Not Defined USBDrv Echo No USB drive connected.&& GoTo :EndIt
    If "%USBDrv:~2%" == "" (GoTo Selected) Else Echo Which USB drive %USBDrv::=: %? 
    For /F "Tokens=2 Delims=?" %%G In ('%SystemRoot%\System32\choice.exe
     /C %USBDrv::=% 2^>NUL') Do Set "USBDrv=%%G:"
    
    :Selected
    Call :Task %USBDrv%
    
    :EndIt
    %SystemRoot%\System32\timeout.exe /T 5 1>NUL 
    GoTo :EOF
    
    :Task
    Rem Place your commands here [%1 will be the USB drive e.g. E:].
    

    All you should need to do is to place your backup command(s) etc. at the bottom.