batch-filedisk-partitioningdrive-letter

Find current diskpart volume number in .bat


Using a .bat script on an USB drive I'd like to change it's drive letter without using 3rd party software and any requirements on the system where the USB is plugged in except that it's Windows XP or higher.

To get the current drive letter I use

set DRIVE=%~dp0

Which is E: for example

Before I can actually change E:'s drive letter, how do I find out the volume number in diskpart's volume list automaticly?

select volume E:

obviously won't work, you can only use the n for the disc number.

EDIT:

Thanks to @wOxxOm for the solution. Here is my final .bat script i now use to auto-change the drive letter of the drive the script is on to U:\

@echo off
set DRIVERAW=%~dp0
set DRIVE=%DRIVER:~0,1%
if %DRIVE%==U exit
for /f "tokens=2,3" %%a in ('echo list volume ^| diskpart') do (
    if %%b==%DRIVE% set VOLNO=%%a
)
del %DRIVERAW%\diskpart.txt
echo select volume %VOLNO% > %DRIVERAW%\diskpart.txt
echo assign letter=U >> %DRIVERAW%\diskpart.txt
echo ^G
diskpart /s %DRIVERAW%\diskpart.txt
exit

You could replace the two U's with any other drive letter you want if it should not be mounted to U:\

Just stay sure that nothing is already mounted on U:\


Solution

  • Parse the list of volumes which looks like this:

    Volume 6 E MY_USB FAT32 Removable 971 MB Healthy

    Run in elevated command prompt or rightclick the .bat file and run as admin.

    for /f "tokens=2,3" %%a in ('echo list volume ^| diskpart') do (
        if %%b==E echo Volume number is %%a
    )
    

    You can also check by volume name (use tokens=2,4) or by volume type (use tokens=2,6), a little trickery with token numbers will be required in case volume name contains spaces.