Powershell – Run PowerShell script with Service Start

affinitypowershellprocess-prioritystartwindows-service

I'd like to set the Affinity and Priority of a service process when it is started (without modifying the service/process code, I don't own the code, it's a 3rd party service).

I know I can do:

$Process = Get-Process MyService
$Process.ProcessorAffinity = 4

in PowerShell to change the Affinity of the process or prefix the command path with:

cmd.exe /c start "Some Process Name" /affinity 4

However, neither of these are applicable to changing the Affinity and Priority of the service's process automatically everytime the service is started) How can I do this without using some 3rd-party app that 'maintains' process affinity across restart (I'd really like to write/create a solution myself and not rely yet another app to 'configure' windows).

Best Answer

Have a look at this post : http://waynes-world-it.blogspot.ca/2009/06/processor-affinity-on-windows-server.html

If you’re trying to control a service, you could use instsrv/srvany to create a service that wraps the start or psexec command around the real service binary. For example, the commands below create another version of the spooler service that will only run on the first processor.

instsrv Test c:\util\srvany.exe 
reg add hklm\system\currentcontrolset\services\test\Parameters
reg add hklm\system\currentcontrolset\services\test\Parameters /v Application /t reg_sz /d cmd.exe 
reg add hklm\system\currentcontrolset\services\test\Parameters /v AppParameters /t reg_sz /d "/c start /affinity 1 C:\WINDOWS\system32\spoolsv.exe"