The empty line is in fact an artefact (an orphaned carriage-return character) that appears when using for /F
to convert the Unicode output of wmic
to ASCII/ANSI text. To get rid of such things just wrap around another for /F
loop*:
@echo off
setlocal EnableDelayedExpansion
for /F "skip=1" %%I in ('wmic LogicalDisk where "DriveType=3" get DeviceID') do (
for /F %%J in ("%%I") do (
set "_DRIVE.LETTERS.USED=!_DRIVE.LETTERS.USED!%%J\ ; "
)
)
endlocal & echo %_DRIVE.LETTERS.USED%
I also removed the options tokens
(default: 1
) and delims
(default: SPACE, TAB) since they are not really needed here any more (splitting off the colon and then re-appending it in the loop body makes no sense).
A more general solution, which even works when there are SPACEs within the values, is to use the /VALUE
option of wmic
, because then the returned values are no longer padded with trailing SPACEs, which is the case without /VALUE
. To split off the preceding value name in the changed output (like DeviceID=C:
), set the appropriate tokens
and delims
options of the inner for /F
loop:
@echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%I in ('wmic LogicalDisk where "DriveType=3" get DeviceID /VALUE') do (
for /F "tokens=1* delims==" %%J in ("%%I") do (
set "_DRIVE.LETTERS.USED=!_DRIVE.LETTERS.USED!%%K\ ; "
)
)
endlocal & echo %_DRIVE.LETTERS.USED%
This would remove any leading equal-to signs from the values, but this is not going to happen with the values at hand anyway, and this should generally happen extremely rarely.
*) This two-loop method is credited to user dbenham ‐ see his answer to Why is the FOR /f loop in this batch script evaluating a blank line? as well as this external article WMIC and FOR /F : A fix for the trailing <CR> problem.