As your minimal code example currently makes little sense to me, also mentioned by Gerhard Barnard, I have decided to post a few code snippets for your information.
I prefer to use Mountvol
for this type of thing. It would certainly help in cases such as an empty optical drive at e.g. D:\
, where If Exist D:\
will fail, but that wouldn't necessarily mean the drive letter D:
is okay to assign to a new drive.
If you're just trying to identify the first mounted drive letter, alphabetically:
@Set "_l="&For /F Tokens^=* %%A In ('MountVol^|Find ":\"^|Sort/R')Do @Set "_l=%%~dA"
@Echo(The first letter assigned to a drive is %_l%&Pause
To identify the last mounted drive letter, alphabetically:
@Set "_l="&For /F Tokens^=* %%A In ('MountVol^|Find ":\"^|Sort')Do @Set "_l=%%~dA"
@Echo(The last letter assigned to a drive is %_l%&Pause
To determine the first available, unmounted, drive letter, alphabetically:
@Set "_l="&For /L %%A In (67 1 90)Do @Cmd/C Exit/B %%A&Call:Sub %%=EXITCODEASCII%%
@Echo(The first available drive letter is %_l%&Pause&Exit/B
:Sub
@If Not Defined _l MountVol|Find "%1:\">Nul||Set "_l=%1:"
And to determine the last available, unmounted, drive letter, alphabetically.
@Set "_l="&For /L %%A In (90 -1 67)Do @Cmd/C Exit/B %%A&Call:Sub %%=EXITCODEASCII%%
@Echo(The last available drive letter is %_l%&Pause&Exit/B
:Sub
@If Not Defined _l MountVol|Find "%1:\">Nul||Set "_l=%1:"
In the latter two examples you can replace 67
with 66
if you wish to include a possible B:
drive, or with 65
if you wish to also include a possible A:
drive, you can also replace it with 68
to exclude the C:
drive.