Orion8
Orion8

Reputation: 53

Why double results when call echo to output to file?

I am trying to generate DiskDevices.ini file about disks/drives.

This is my batch.

@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
SET "InputFile=DiskDevices.ini"
IF EXIST "%InputFile%" (DEL /f /q "%InputFile%")
SET /A "TotalDevices=0"
SET /A "Index=0"
@FOR /F "skip=2 tokens=*" %%G IN ('
"WMIC PATH Win32_DiskDrive GET Index /format:csv 2>NUL"
') DO (
    SET /A "TotalDevices=TotalDevices+1"
    SET /A "Index=Index+1"
    >>"%InputFile%" CALL ECHO [Device_%%Index%%]
    @FOR /F Tokens^=* %%G IN ('
    "WMIC PATH Win32_DiskDrive GET Caption,Size /value 2>NUL"
    ') DO (
        @FOR /F Tokens^=* %%H IN ("%%G") DO (>>"%InputFile%" CALL ECHO %%H)
        )
)
>>"%InputFile%" CALL ECHO [Total Devices]
>>"%InputFile%" CALL ECHO Value=%%TotalDevices%%
PAUSE

Results is loop two times.

[Device_1]
Caption=Samsung EVO
Size=162536803840
Caption=Kingston USB Device
Size=31718510080
[Device_2]
Caption=Samsung EVO
Size=162536803840
Caption=Kingston USB Device
Size=31718510080
[Total Devices]
Value=2

I need same this:

[Device_1]
Caption=Samsung EVO
Size=162536803840
[Device_2]
Caption=Kingston USB Device
Size=31718510080
[Total Devices]
Value=2

Thanks for help.

Upvotes: 0

Views: 411

Answers (2)

aschipfl
aschipfl

Reputation: 34909

Well, you have nested two for /F loops that are gathering basically the same information, that is why you get duplicates.


What about this approach, which uses the Index property for the [Device_#] header as well as for a where clause of the inner wmic query:

@echo off
set "COUNT=0"
> "DiskDevices.ini" (
    for /F "delims=" %%J in ('wmic DiskDrive get Index /VALUE 2^> nul') do (
        for /F "tokens=2 delims==" %%I in ("%%J") do (
            echo [Device_%%I]
            for /F "delims=" %%H in ('wmic DiskDrive where "Index=%%I" get Caption^,Size /VALUE 2^> nul') do (
                for /F "delims=" %%G in ("%%H") do (
                    echo(%%G
                )
            )
            set /A "COUNT+=1"
        )
    )
    echo [Total Devices]
    call echo Value=%%COUNT%%
)

Upvotes: 2

montonero
montonero

Reputation: 1731

Because you're getting the list of devices twice. Do everything in one loop or add a where condition with Index value to the second wmic call to filter out the other devices.

Upvotes: 0

Related Questions