Powershell – Process CPU Affinity

There are cases when we want to control how much CPU a particular process can consume.
Current servers are mostly having more then one processor therefore one of the quickest ways of limiting CPU allocation is by setting CPU affinity for the process.

This particular script was written for the Citrix XenApp environment where it was identified that sometimes Internet Explorer was consuming all the avilable CPU and as a result slow down the whole server. Users are not happy 🙂
By setting only one processor for the IE process we can isolate the issue [at least to some degree].

#Get the time for logging purposes
$D = Get-Date
$T = '' + $D.ToShortDateString() + ' ' + $D.ToShortTimeString()

#Select only iexplore proceses
$Proccesses = Get-Process | ? {$_.Name -eq "iexplore"}

#For each iexplore process do
foreach ($Proccess in $Proccesses)
{
    #Find current CPU utilization
    $CPUUtil = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process | ? { $_.idprocess -eq $Proccess.id }).PercentProcessorTime

    '' + $CPUUtil + '% - ' + $Proccess.id 

    #If CPU is higher then 50 then change process affinity to use only second core [there must be at least two cores]
    if ($CPUUtil -gt 20)
    {
        Get-Process -id $Proccess.id | 
        %{
            #$_.ProcessorAffinity; 
            
            if ($_.ProcessorAffinity -ne 2)
            {
                #'Changing from ' + $_.ProcessorAffinity + ' to 2'
                $_.ProcessorAffinity = 2; 
                '' + $T + ': ' + $CPUUtil + '% CPU, ' + $Proccess.id + ' PID, ' + $Proccess.Name + ', CPU Affinity for the process "' + $Proccess.id + '" is set to ' + $_.ProcessorAffinity + ' because of ' + $CPUUtil + '% CPU utilization' >> C:\Temp\ControlProcessesAffinity_Log.txt
            }
            else
            {
                '' + $T + ': ' + $CPUUtil + '% CPU, ' + $Proccess.id + ' PID, ' + $Proccess.Name + ', Affinity have already been set for this process to 2, current value is: ' + $_.ProcessorAffinity >> C:\Temp\ControlProcessesAffinity_Log.txt
            }
        }
    }
}
Advertisements

Leave a Comment here

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s