Tuesday, October 02, 2012

Windows Process Affinity

Yesterday I had a new challenge: to change the Processor Affinity through PowerShell.
Processor Affinity in another term for "what cores can my process use". By limiting a CPU hungry process to just use some of the available cores, it is possible to let other processes run more smoothly.
This can easily be accomplished by right-clicking a process in TaskManager, but can it be done by a script?

The answer is ... Yes.

The result was  this small PowerShell function:

Function Set-Affinity {
                             ## id can be either a PID or a processname
                             ## affinity is a bitmask, with the first core being 1, the next 2, then 4, 8, 16 etc.
                             ## To use core number 1,2 and 4 the affinity must be set to 7 (1 + 2 + 4)
                             Param (
                                                          $id = $pid,
                                                          $affinity = 1
                             )
                             If (($id.gettype()).name -eq "int32") {
                                                          $processes = Get-Process -id $id
                             } ElseIf (($id.gettype()).name -eq "String") {
                                                          $processes = Get-Process -name "$id"
                             }                          
                             foreach ($p in $processes) {
                                                          $p | Add-Member Noteproperty OldProcessorAffinity -value $p.ProcessorAffinity
                                                          $p.ProcessorAffinity = $affinity
                                                          $p | Select Id, ProcessName, CPU, OldProcessorAffinity, ProcessorAffinity
                             }
}  

Example (setting the affinity of all "PowerShell" processes to 1 - ie. 1 core maximum):

Set-Affinity PowerShell 1
           

No comments: