Search code examples
batch-filecmdechowmiwmic

Why FOR LOOP only output Echo is on in txt file?


My cmd batch file always output:

ECHO is on.
ECHO is on.
ECHO is on.

The script:

SET "InputFile=abc.txt"
IF EXIST "%InputFile%" (DEL /f /q "%InputFile%")
SETLOCAL EnableExtensions EnableDelayedExpansion
FOR /F Tokens^=* %%G IN ('
    "WMIC PATH Win32_DiskPartition WHERE ^(DeviceID^="Disk #0, Partition #1"^) Assoc:list /AssocClass:Win32_LogicalDiskToPartition 2>NUL"

') DO (CALL ECHO %%G>> "%InputFile%")

ENDLOCAL

How to fix?.


Solution

  • 1. The WHERE clause in WQL fails if contains a comma. Use

    "… WHERE ^(DeviceID^ like^ "Disk #0_ Partition #1"^) …
    

    2. There is a known wmic bug, see Dave Benham's article WMIC and FOR /F: A fix for the trailing <CR> problem. Fix it e.g. as follows:

    @ECHO OFF
    SETLOCAL EnableExtensions EnableDelayedExpansion
    SET "InputFile=abc56715419.txt"
    IF EXIST "%InputFile%" (DEL /f /q "%InputFile%")
    REM SETLOCAL EnableExtensions EnableDelayedExpansion
    (
    FOR /F Tokens^=* %%G IN ('
        "WMIC PATH Win32_DiskPartition WHERE ^(DeviceID^ like^ "Disk #0_ Partition #1"^) Assoc:list /AssocClass:Win32_LogicalDiskToPartition 2>NUL"
    ') DO ( for /F "delims=" %%g in ("%%G") do (CALL ECHO(%%g))
    )>>"%InputFile%"
    REM debugging output
    type "%InputFile%"
    ENDLOCAL
    

    Here the for loops are

    • %%G to retrieve the WMIC output;
    • %%g to remove the ending carriage return in the values returned: wmic behaviour: each output line ends with 0x0D0D0A (<CR><CR><LF>) instead of common 0x0D0A (<CR><LF>).