Search code examples
batch-filescriptingwmic

Get the result of a WMIC command and store it in a variable


I have seen some batch scripts working that way, including all around stackoverflow.

My question is simple: Why the MEM part isn't working?

@echo OFF

SET CPU="$CPU"

echo CPU: %NUMBER_OF_PROCESSORS%

FOR /F "delims=" %%i IN ('wmic computersystem get TotalPhysicalMemory') DO set MEM=%%i

echo MEM: %MEM%

Solution

  • That's simple. wmic computersystem get TotalPhysicalMemory outputs three lines of text:

    TotalPhysicalMemory
    12867309568
    <blank line>
    

    So your for-loop does three iteration. In the first one MEM is set to TotalPhysicalMemory, in the second one it's set to 12867309568 and finally it becomes . So your output is empty.

    This is quite ugly but will solve your problem:

    @echo OFF
    setlocal enabledelayedexpansion
    SET CPU="$CPU"
    echo CPU: %NUMBER_OF_PROCESSORS%
    FOR /F "delims= skip=1" %%i IN ('wmic computersystem get TotalPhysicalMemory') DO (
        set MEM=%%i
        goto STOP
    
    )
    :STOP
    echo MEM: !MEM!
    

    skip=1 will ignore TotalPhysicalMemory and goto STOP will break the loop after the first iteration.