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 (
)
If (($id.gettype()).name -eq "int32") {
} ElseIf (($id.gettype()).name -eq "String") {
}
foreach ($p in $processes) {
}
} Example (setting the affinity of all "PowerShell" processes to 1 - ie. 1 core maximum):
Set-Affinity PowerShell 1