windowspowershellwindows-10cpu

How can I get the number of CPU cores in Powershell?


Suppose I'm running a PowerShell session on a Windows machine.

Is there a one-liner I could use to get:

  1. The number of physical processor cores and/or
  2. The max number of in-flight threads, i.e. cores * hyper-threading factor?

Note: I want just a single number as the command output, not any headers or text.


Solution

  • Note:


    Ran Turner's answer provides the crucial pointer, but can be improved in two ways:

    Therefore:

    # Creates a [pscustomobject] instance with 
    # .NumberOfCores and .NumberOfLogicalProcessors properties.
    $cpuInfo =
      Get-CimInstance –ClassName Win32_Processor | 
         Select-Object -Property NumberOfCores, NumberOfLogicalProcessors
    
    # Save the values of interest in distinct variables, using a multi-assignment.
    # Of course, you can also use the property values directly.
    $coreCountPhysical, $coreCountLogical = $cpuInfo.NumberOfCores, $cpuInfo.NumberOfLogicalProcessors
    

    Of course, if you're only interested in the values (CPU counts as mere numbers), you don't need the intermediate object and can omit the Select-Object call above.

    As for a one-liner:

    If you want a one-liner that creates distinct variables, without repeating the - costly - Get-CimInstance call, you can use an aux. variable that takes advantage of PowerShell's ability to use assignments as expressions:

    $coreCountPhysical, $coreCountLogical = ($cpuInfo = Get-CimInstance -ClassName Win32_Processor).NumberOfCores, $cpuInfo.NumberOfLogicalProcessors