Windows + Powershell: How to change Processor Affinity for all java.exe instances?
5,700
You have to loop over each object to set its ProcessorAffinity
| % {}
in PowerShell means ForEach-Object
and is basically the same as a foreach()
statement in other languages
as root said, you can remove the variable so your code gets shorter.
from a cmd window:
PowerShell "get-process java | % { $_.ProcessorAffinity=11 }"
in a batch file (the batch file handles %
like a variable, so you need to write it 2 times or switch to foreach
) :
PowerShell "get-process java | %% { $_.ProcessorAffinity=11 }"
PowerShell "get-process java | foreach { $_.ProcessorAffinity=11 }"
directly in PowerShell:
get-process java | % { $_.ProcessorAffinity=11 }
Related videos on Youtube
Comments
-
adamitj over 1 year
Based on this question at StackOverflow, I'm able to change processor affinity if an executable is running only in 1 instance with this command:
PowerShell "$Process = Get-Process java; $Process.ProcessorAffinity=11"
If 2 or more instances are running, I cannot change, and this is the output
C:\PowerShell "$Process = Get-Process java; $Process.ProcessorAffinity=11" The property 'ProcessorAffinity' cannot be found on this object. Verify that the property exists and can be set. At line:1 char:30 + $Process = Get-Process java; $Process.ProcessorAffinity=11 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : PropertyAssignmentException
Does anyone knows how to change Processor Affinity for all java.exe instances using Powershell?
-
adamitj over 7 yearsTotally successful! Worked like a charm. And thank you for the explanation about | % {}, that's what I needed.
-
adamitj over 7 yearsJust a correction: When calling from inside a batch file the percent sign must be doubled:
PowerShell "get-process java | %% { $_.ProcessorAffinity=11 }"
-
SimonS over 7 years@adamitj are you sure? that wouldn't make any sense at all, since you would double the
Foreach-Object
. If I run that with%%
I get an error. with%
it works. -
adamitj over 7 yearsYes, for sure. A single percent sign inside a batch file is intended to reference an argument passed outside (calling from OS or from cmd.exe) as in %1, %2, or referencing another environment variable like %tmp%, etc. If I want to print one percent sign with echo, for example, I need to
echo %%
-
SimonS over 7 years@adamitj you're right! the bat-file doesn'0t behave the same as the cmd window itself. I will update my answer