Search code examples
windowscmdwmic

How to compare the return value of WMIC by an IF condition?


This is the console input/output:

C:\Users\>for /f "tokens=* skip=1" %a in ('wmic cpu get numberOfCores') do (set valor="%a")

" ) sers\> (set valor="4

" ) sers\> (set valor="

C:\Users\>set cpu=%valor:~6,-1%

C:\Users\>if "%cpu%" geq "4" (echo yes) else (echo no)
no

The loop seems to iterate twice, assigning the correct value (4) first and then overwriting it a blank value, thus clearing it, leading to a failed comparison with 4.

Why is this happening, and how can I fix this so that the condition returns yes?


Solution

  • You do not need to return the result, save it as a variable, then compare it.

    You can allow the WMI Query Language to determine if the value is:

    • Equal To 4
    wmic cpu where numberofcores^=4
    wmic cpu where "numberofcores = 4"
    
    • Greater Than 3
    wmic cpu where numberofcores^>3
    wmic cpu where "numberofcores > 3"
    

    Greater Than OR Equal To 4.

    wmic cpu where numberofcores^>^=4
    wmic cpu where "numberofcores >= 4"
    

    Putting those together into a format more akin to your posted intent:

    wmic cpu where numberofcores^>3 get numberofcores /value 2>nul|find "NumberOfCores">nul&&(echo yes)||echo no
    

    Or using more correct/robust, syntax:

    %SystemRoot%\System32\wbem\WMIC.exe CPU Where "NumberOfCores >= 4" Get NumberOfCores /Value 2>NUL | %SystemRoot%\System32\find.exe "NumberOfCores" 1>NUL && (Echo Yes) || Echo No