Automate Drive Letter Assignment with a DiskPart Script

To assign drive letters, I initially relied on the Disk Management console (diskmgmt.msc). While the task seemed simple, repeating it after each fresh Windows installation became time-consuming. To streamline the process, I developed a Batch script that automates drive letter assignments using embedded DiskPart commands. In this post, I focus specifically on the DiskPart-related aspects. You can view the complete script by visiting the project on GitHub.

1. Assigning an Unavailable Letter to a Partition

This is the problem my Batch script was designed to solve. When using the Disk Management interface to change a drive letter, the dropdown menu only displays letters that are currently available. Similarly, DiskPart throws an error if a user tries to assign a letter that is already in use by another partition — other than the one being modified.

The solution can be summarized as follows: if the desired drive letter is already in use, first remove it from its current owner, then assign it to the target partition. This logic is implemented using DiskPart's remove and assign commands.

1.1 Setting a Partition's Drive Letter in DiskPart

There are two main approaches to identifying the target partition using the DiskPart tool:

  • By disk and partition number.
    This selects partition 2 on disk 1.

    select disk=1
    select partition=2
  • By volume name.
    This selects the partition associated with the volume letter D.

    select volume=D

After shifting the focus to the partition, we then apply either, a remove or assign commands.

I have a preference for selecting a partition using its drive letter for removing the same letter. Since, we do not need to specify it in the remove command.

select volume=D
remove

However, this operation should be performed only once, as repeated executions may unintentionally alter the mount point configuration. To avoid this, it's safer to explicitly specify the drive letter to remove:

remove letter=D

The reverse operation — assigning the drive letter — is similar, regardless of whether the partition was selected by disk/partition number or volume name:

assign letter=D

or

assign

The second assign command, where no letter is specified, instructs the system to assign the next available letter in alphabetical order. While this behavior may seem random, it is deterministic —the system always chooses the first unassigned letter starting from C onward.

1.2 Retrieving the Volume's Index in DiskPart

While disk and partition numbers are consistent across the Windows system, volume indexes are specific to each DiskPart session. This distinction is important: once a drive letter is removed, the associated volume can no longer be selected by that letter — so its index must be cached beforehand if you want to continue working with it in the same script.

Here's a technique to extract and store the volume index before removing the drive letter:

  1. Create a simple DiskPart script
    Open Command Prompt as administrator and create a script named dp-script containing a select volume=D command. Press Enter to insert a new line, then press Ctrl+C to finish:

    > type con > dp-script
    select volume=D
  2. Execute the script and redirect the output
    Run DiskPart with the script and redirect its output to a file named dp-out:

    > diskpart /s dp-script > dp-out

    If the volume D is the 7th volume in the list, this will be the dp-out file content:

    Microsoft DiskPart version 10.0.19041.3636
    Copyright (C) Microsoft Corporation.
    On computer: DESKTOP-V71EMTX
    
    Volume 7 is the selected volume.
  3. Parse the content with for /f to return the index.
    This command looks for a line starting with Volume, extracts the second token (7), and echoes it to the console.

    > for /f "tokens=2" %i in ('type dp-out ^| findstr /b "Volume"') do @echo %~i
    7

This technique ensures that you can continue identifying and manipulating the target volume even after its drive letter has been removed.

2. Batch Scripting the Solutions

The functions below are part of the custom drive letter assigner project.

I won't go into detail here on how I retrieve the disk and partition numbers, as that part is handled via WMI command-line tools.

:getVolumeIndex
This function returns the volume index for a specified drive letter using the exit code. The logical AND operator ensures that the DiskPart command is only executed if the script file was successfully created in the temporary directory %TEMP%. Additionally, note that steps 2 and 3 from the previous section have been merged into a single for /f loop.

swap.bat
:getVolumeIndex <%1 = drive letter>
setlocal
cmd /c exit -1
set dpScript=%TEMP%\dp-script&
echo select volume=%~1 > "%dpScript%" && for /f "tokens=2" %%i in ('diskpart /s "%dpScript%" ^| findstr /b "Volume"') do cmd /c exit %%~i
endlocal
exit /b

:setVolumeDriveLetter
This function modifies the drive letter for a volume, which is identified either by its current drive letter or volume number. It supports both removal and assignment via the second parameter. In addition to using the logical AND operator for command chaining, the find command is used to manipulate the exit code — since diskpart only returns an error code in the case of a syntax error, not for logical failures.

swap.bat
:setVolumeDriveLetter <%1 = volume specifier> <%2-4 = remove/assign command>
setlocal
set dpScript=%TEMP%\dp-script&
(
  echo select volume=%~1
  echo %~2 %~3 %~4
) > "%dpScript%" && diskpart /s "%dpScript%" | find "successfully" > nul
endlocal
exit /b

:setPartitionDriveLetter
This function sets or removes the drive letter for a partition, identified by its disk number and partition number. Its structure closely mirrors that of the previous function.

assign.bat
:setPartitionDriveLetter <%1 = disk number> <%2 = partition number> <%3-5 = remove/assign command>
setlocal
set dpScript=%TEMP%\dp-script&
(
  echo select disk=%~1
  echo select partition=%~2
  echo %~3 %~4 %~5
) > "%dpScript%" && diskpart /s "%dpScript%" | find "successfully" > nul
endlocal
exit /b

3. Usage

Let's demonstrate how to swap drive letters between two volumes, H: and D:, where both letters are currently unavailable (i.e., already in use). This task is accomplished using the :getVolumeIndex and :setVolumeDriveLetter functions inside a batch script:

swap.bat
call :getVolumeIndex D
set volumeIndex=%errorlevel%&
call :setVolumeDriveLetter D remove
call :setVolumeDriveLetter H assign letter=D
call :setVolumeDriveLetter %volumeIndex% assign letter=H

Now, let's say you want to reassign the drive letter D, which is currently used by the partition (Disk 1, Partition 2), to a different partition (Disk 1, Partition 1) — all done using only :setPartitionDriveLetter.

assign.bat
call :setPartitionDriveLetter 1 2 remove letter=D
call :setPartitionDriveLetter 1 1 assign letter=D
call :setPartitionDriveLetter 1 2 assign

4. Conclusion

Manually reassigning drive letters after every clean Windows installation can be tedious and error-prone — especially for users who rely on a consistent file structure across setups. By leveraging DiskPart through scripting, I was able to automate this process and ensure predictable, repeatable results.

This project has been a valuable learning experience in scripting, Windows system internals, and automation — skills that are immediately useful for both personal setups and more advanced system administration tasks.

You can find the full source code on GitHub. If you find it helpful or have suggestions, feel free to contribute or open an issue!

Comments

Popular posts from this blog

Retrieve the Current Command Prompt Process Identifier Using PowerShell

Mutual Exclusion Techniques for Batch Scripts