Controlling Process Priority and Processor Affinity

by Dec 18, 2012

When you get yourself a process using Get-Process, what you get back is an object that has useful methods and writeable properties.

This line will assign a high priority to your current PowerShell host and would run on all four CPU cores (provided your machine has four cores):

$process = Get-Process -id $pid
$process.Priority = 'High'
$process.ProcessorAffinity = 15

ProcessorAffinity really is a bitmask where each bit represents one CPU core. Since Windows won't limit default processes to a specific CPU core, you can use this property also to find out how many CPU cores your machine has:

PS> [System.Convert]::toString([int]$process.ProcessorAffinity, 2)

It is admittedly a creative approach, but to find out the number of CPUs, you'd have to count the bits, and once you convert the bits to a string, that's the length of the string:

PS> $cpus = ([System.Convert]::toString([int]$process.ProcessorAffinity, 2)).Length
PS> "Your machine has $cpus CPU (cores)."
Your machine has 4 CPU (cores).

Twitter This Tip! ReTweet this Tip!