Home > OS >  How to get the number of physical and logical cores in a batch file?
How to get the number of physical and logical cores in a batch file?

Time:04-14

WMIC CPU Get NumberOfCores,NumberOfLogicalProcessors gets me most of what I want, but how do I store the output into a variable?

Also, in the case of a dual socket machine, will this return all combined cores?

CodePudding user response:

To get a command's output, use a for /f loop:

for /f "delims=" %%a in ('"WMIC CPU Get NumberOfCores,NumberOfLogicalProcessors /value"') do set /a "_%%a"
set _

Parsing wmic output has some quirks (unicode, strange line ending CRCRLF), and there are several methods to get the format you want. As here the values are pure numeric, I chose set /a. This won't work if the values are alphanumeric.

CodePudding user response:

for /f "tokens=1,2delims==" %%b in ('"WMIC CPU Get NumberOfCores,NumberOfLogicalProcessors /value"') do set /a "%%b=%%c" 2>nul
SET numberof

The two WMIC report lines of interest have format item=value, value is numeric so set /a can be used. The 2>nul suppresses the errormessages generated by processing the other lines.

note that there is also a system-established variable NUMBER_OF_PROCESSORS

CodePudding user response:

If you happen to be on a system without wmic (like some versions of Windows 11) you can use powershell to do this in a batch script:

for /f "skip=2 tokens=*" %%g in ('%__APPDIR__%WindowsPowerShell\v1.0\powershell.exe -noprofile /command "Get-WmiObject -class Win32_processor | ft NumberOfCores"') do set "_numCores=%%g"
echo Number of Cores: %_numCores%
echo Number of Logical Processors: %NUMBER_OF_PROCESSORS%

Note: Now simplified with Compo's helpful suggestions.

  • Related