Find an unused drive letter in Batch script

When working with batch scripts, it is sometimes useful to find the first free drive letter automatically. This is especially helpful in scripts that mount temporary network paths, map local resources, or prepare a workspace without hardcoding a drive letter that may already be in use.

The following batch script checks a list of drive letters and stores the first available one in the variable %LW%

@echo off %debug%
if not "%OS%"=="Windows_NT" exit /b
setlocalset ll=V T R Q P O N M K J I W X Y Z L U S H G F E D
for %%l in (%ll%) do (
 set LW=%%l
 mountvol %%l: /L >nul
 if errorlevel 1 (
 subst | findstr /B "%%l:" > nul
 if errorlevel 1 (
 net use %%l: >nul 2>&1
 if errorlevel 1 goto gotone
 )
 )
)
echo No unused drive letter found
exit /b
:gotoneecho %LW% is an unused drive leter

How the script works

The script begins by checking whether it is running on Windows NT-based systems. If not, it exits immediately. This prevents the script from running in an unsupported environment.

Next, it defines a list of drive letters to test. The letters are checked in a custom order, which can be adjusted depending on your own preferences. The script then loops through each letter and tests whether it is already in use.

Three different checks are performed:

  • mountvol %%l: /L checks whether the letter is assigned to a volume.
  • subst is used to check for substituted drives.
  • net use is used to check for mapped network drives.

If all three checks fail, the letter is considered free and the script jumps to the gotone label.

The result

As soon as a free drive letter is found, the script stores it in %LW%. That means you can use this variable later in the same batch file for additional commands, such as mapping a drive or assigning a temporary mount point.

Example:

textecho Using drive letter %LW%

Why this is useful

This approach is practical because it avoids hardcoding a drive letter that might already be in use. It also makes batch scripts more flexible in environments where drive letters can vary from system to system.

For administrative scripts, deployment tasks, or temporary mappings, this is a simple and effective solution.

Schreibe einen Kommentar