Wednesday, February 16, 2011

How to set the Windows Process Priority via Powershell and WMI

Sometimes you want to increase or decrease the priority of a windows service e.g. if you have single-core QA VMWare instances with limited capacity. This can be done via powershell quite easily

(get-wmiobject Win32_Process | where { $_.Name -eq "fabric_keeper.exe"}).SetPriority(32768)

You can get the list of valid values for the Process priority from MSDN. Make sure to check the return value
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 5
Return code Description
0 .. Successful completion
2 .. Access denied
3 .. Insufficient Privilege
8 .. Unknown Failure
9 .. Path Not Found
21 .. Invalid Parameter
In our case it was Access Denied and Insufficent Priviledge. A workaround would be to run the powershell as NT Authority\LOCAL SYSTEM. The easiest and most reliable way is to use psexec from the Windows SysInternals.

psexec -i -s C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe

Execute the command again and you should get

__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 0