Search code examples
windowsbatch-filevariablesinvisible

Displaying %variables% is blank/missing when running a batch file in Windows


OK, inside of my BAT (batch) file I am trying to detect the number of physical cores of the Windows machine, then display that to the user. I am using 'wmic' which I have confirmed is working properly in a command prompt in retuning the correct information. However, when I try to display the value I have stored, it just shows a blank space.

For example, when I run this, the last line just shows "You have physical cores", and there is just a space between the word "have" and "physical", even though that's where the value of %cpuvar2% is supposed to be showing. I cannot figure out why this is not showing. I have tried with @ECHO ON as well, but no luck.

:labelCPU
@ECHO OFF

REM Intro message to let the user know what is happening
ECHO Detecting CPU cores...

REM Command to get the number of physical cores and store as a string var
wmic computersystem get numberoflogicalprocessors> cpuvar

REM Command to remove the first line of junk text from the returned string and save as a new var
MORE +1 cpuvar> cpuvar2

REM Output the number of physical cores to the user
ECHO You have %cpuvar2% physical cores!

System: Windows 10 Pro, x64


Solution

  • Here's a quick example for you to study.

    @Echo Off
    SetLocal EnableExtensions DisableDelayedExpansion
    
    Echo Detecting CPU cores...
    Set "NumCores=0"
    For /F EOL^=N %%G In ('%SystemRoot%\System32\wbem\WMIC.exe
     ComputerSystem Get NumberOfLogicalProcessors 2^>NUL'
    ) Do For /F "Tokens=*" %%H In ("%%G") Do Set "NumCores=%%H"
    Echo You have %NumCores% physical cores!
    
    Pause