SQL Tuning MAXDOP
April 14, 2025
SQL Tuning MAXDOP
April 14, 2025

PowerShell | Affinity

in this article we're going to talk about Affinity

Affinity is a great way to control processes and scripts in keeping them from consuming a server or impacting a production process..

When your designing a PowerShell script that say scans for a file or run multiple installs, or a task that can potentially consume and entire server to peek at 90-100% leaving it slow or non responding, can be a challenge when pulling this off in a production environment. 

Using Affinity allows you to "pin" your script to specific cores in the server. This allows you to control how much of the server you will consume when running your task. 


This is called a CPU MASK.
The Processor Affinity value is a bitmask, where each bit corresponds to the processor core number.
For Demonstration using a 8 core processor system:

Individual Binary Mask Addressing
Core 0 | 00000001
Core 1 | 00000010
Core 2 | 00000100
Core 3 | 00001000
Core 4 | 00010000
Core 5 | 00100000
Core 6 | 01000000
Core 7 | 10000000

The Furthest to the right placement is the lowest core.  00000000

You can be selective too. 
Say you want to have your process run under only cores 1 and 3?  "00001010"
How about only the last two cores on a 8 core server? "11000000"
the Process will only execute on the placement represented by 1's
*remember we're counting from 0-7

So to use this you can run the following command example.
start /affinity 0x00000000000000C0 notepad.exe 

Your probably thinking, That doesn't look like what we just learned. 
This is because the /Affinity uses Hex values.

To get this you simply open calculator and switch to programmer then select the BIN field and enter the desired bit mask.
It will show you the Hex value you need for affinity to work properly.

* Tip
If the general population of servers are 4 or 8,12,16 core VM?s 
You can use a bitmask of 0x0000000000008888 or BITMASK 1000 1000 1000 1000
When executed on a lower core it will only use the last core and ignore the upper bit mask

  •  4 Core will execute on the last core 3
  • 8 Core it will execute on cores 3 & 7 
  • 16 Core?  It will execute on 3 , 7, 11 ,15


*Remember Core 0 is the first core. 

*Tip- when planning
Avoid running your task on core 0 which is where the main Kernel OS lives  and also the Antivirus us usually there too.

Your OS will thank you. This also Extends to SQL Admins. in SQL you can set the BIT mask as well.
It helps SQL too, When a transaction log "grow" command is issued? it gives the OS room to execute will make it complete that much faster.