Search code examples
for-loopbatch-filevariablesdiskwmic

Get variable value from for loop in batch file


I am trying to list inline partitions separated by plus sign. Code below make that for me, but at the end of course is the last one plus. It's any possibility to remove it (last plus) and save it to variable that I can use later in script?

@echo off
for /f "tokens=2 delims==" %%d in ('wmic logicaldisk get name /format:value') do @echo | set /p drives=%%d+

Solution

  • The simplest idea is to use a variable, ensure it is not defined before you begin, then only prefix each drive letter with the + character, if that variable is already defined.

    Example:

    @Echo Off
    SetLocal EnableExtensions DisableDelayedExpansion
    Set "DriveList="
    For /F Tokens^=2^ Delims^=^" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe
     LogicalDisk Assoc /ResultRole:DeviceID 2^>NUL') Do If Defined DriveList (
        SetLocal EnableDelayedExpansion & For %%H In ("!DriveList!") Do EndLocal ^
        & Set "DriveList=%%~H+%%G") Else Set "DriveList=%%G"
    Echo(%DriveList%
    Pause
    

    It looks as if you may wish to use Set /P instead of Echo(, although why you would want a string like C:+D:+E:+G: is another matter!