Search code examples
windowsbatch-filecmdwmic

Removing Last Empty Entry After Getting Drive List - Batch Script


Here is my batch script which gives you the list of hard drive letters:

@echo off
setlocal enabledelayedexpansion
for /f "skip=1 tokens=1,2 delims=: " %%a in ('WMIC LogicalDisk Where "DriveType='3'" Get DeviceID') do (
   set "_DRIVE.LETTERS.USED=!_DRIVE.LETTERS.USED!%%a:\ ; "
)
echo %_DRIVE.LETTERS.USED%

My expected output is: C:\ ; D:\ But it will print C:\ ; D:\ ; :\ ;

How to remove last extra :\ ;?


Solution

  • Filter for the relevant lines: ... Get DeviceID^|find ":"') do ... to get rid of empty entries and echo %_DRIVE.LETTERS.USED:~0,-3% to delete the last space/semicolon/space:

    @echo off
    setlocal enabledelayedexpansion
    for /f "skip=1 tokens=1,2 delims=: " %%a in ('WMIC LogicalDisk Where "DriveType='3'" Get DeviceID ^|find ":"') do (
       set "_DRIVE.LETTERS.USED=!_DRIVE.LETTERS.USED!%%a:\ ; "
    )
    echo %_DRIVE.LETTERS.USED:~0,3%