Find current diskpart volume number in .bat

6.9k Views Asked by At

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:\

3

There are 3 best solutions below

7
On BEST ANSWER

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.

0
On

The Third line in the batch file, set DRIVE=%DRIVER:~0,1% should be, set DRIVE=%DRIVERAW:~0,1%

With that change it works for me.

0
On

Much more easiear as You think :) Not documented, but working!

SELECT VOLUME E

Just use the volume letter instead of number...

See my result:

C:\Temp>diskpart

Microsoft DiskPart version 10.0.19041.964

Copyright (C) Microsoft Corporation.
On computer: DESKTOP-H6E03H5

DISKPART> select volume e

Volume 3 is the selected volume.

DISKPART> list volume

  Volume ###  Ltr  Label        Fs     Type        Size     Status     Info
  ----------  ---  -----------  -----  ----------  -------  ---------  --------
  Volume 0     C                NTFS   Partition   1862 GB  Healthy    Boot
  Volume 1         Helyreállít  NTFS   Partition    529 MB  Healthy    Hidden
  Volume 2                      FAT32  Partition     99 MB  Healthy    System
* Volume 3     E                NTFS   Removable    232 GB  Healthy
  Volume 4     D                RAW    Removable    232 GB  Healthy

DISKPART>