windowsbatch-fileaffinity

Change affinity of process with windows script


In Windows, with

 START /node 1 /affinity ff cmd /C "app.exe"

I can set the affinity of app.exe (number of cores used by app.exe).

With a windows script, How I can change the affinity of a running process ?


Solution

  • PowerShell can do this task for you.

    Get Affinity
    $Process = Get-Process app
    $Process | Select-Object ProcessorAffinity
    
    Set Affinity
    $Process = Get-Process app
    $Process.ProcessorAffinity = 255
    

    Example ( 8 Core Processor )

    Core # Value BitMask
    Core 1 1 0x00000001
    Core 2 2 0x00000010
    Core 3 4 0x00000100
    Core 4 8 0x00001000
    Core 5 16 0x00010000
    Core 6 32 0x00100000
    Core 7 64 0x01000000
    Core 8 128 0x10000000

    Just add the decimal values together for which core you want to use.

    Using with cmd.exe

    You can use the PowerShell code from within the cmd shell by calling the PowerShell process with the code as an argument. Separate commands with a semi-colon.

    > powershell.exe "Get-Process notepad++ | Select-Object ProcessorAffinity"
    
                                                             ProcessorAffinity
                                                             -----------------
                                                                           255
    
    
    > powershell.exe "$p = Get-Process notepad++; $p.ProcessorAffinity = 13"
    
    > powershell.exe "Get-Process notepad++ | Select-Object ProcessorAffinity"
    
                                                             ProcessorAffinity
                                                             -----------------
                                                                            13
    

    Source

    Here is a nicely detailed post on how to change a process's affinity:

    Setting Processor Affinity @ EnergizedTech
    archive.today / archive.org
    (the broken images weren't important)