PowerShell script that runs in background changing specific process priority to low whenever it is ran

2.6k views Asked by At

I am trying to deploy a script via our Group Policy that will run in the background and watch for a process called "3dsmax.exe". Each time this process is started, I want to make sure it's priority level is set to "low".

My Powershell understanding is extremely limited. I tried combining the following using different forums but that does not seem to work and I beleive this will terminate after first occurrence which is not preferable. I use "calc.exe" as a testing process.

#requires -version 2.0

Register-WmiEvent -Class win32_ProcessStartTrace -SourceIdentifier processStarted



$prog = 'calc.exe'
$newEvent = Wait-Event -SourceIdentifier processStarted

If ($progs -match $newEvent.SourceEventArgs.NewEvent.ProcessName)
{ 
    $prog = Get-Process -Name calc
    $prog.PriorityClass = [System.Diagnostics.ProcessPriorityClass]::Low
}

Any help would be super:)

2

There are 2 answers

4
Knuckle-Dragger On

Here is an alternative method. The "::Low", was not recognized when I tested, had to use ::Idle. EDIT: added foreach ? | loop to suppress error in case of multiple instances. Added Idle loop to begin of script to catch any pre-existing processes upon open.

$prog = Get-Process -Name calc | ?{$_.PriorityClass = [System.Diagnostics.ProcessPriorityClass]::Idle}

    while($true)
    {
        $Query = "select * from __instanceCreationEvent within 1 where targetInstance isa 'win32_Process' AND TargetInstance.Name = 'calc.exe'"
            $Eventwatcher = New-Object management.managementEventWatcher $Query

            $Event = $Eventwatcher.waitForNextEvent()

            $prog = Get-Process -Name calc | ?{$_.PriorityClass = [System.Diagnostics.ProcessPriorityClass]::Idle}
    }

And here is a little .vbs snip to open the app invisibly, so your users don't get a powershell window.

command = "powershell.exe -nologo -command C:\IDLER.ps1"
set shell = CreateObject("WScript.Shell")
shell.Run command,0
0
user3120834 On

Will this be a good way to go about this? It seems to work, but I am not sure this is a good way of entering an endless loop with the aforementioned concerns.

while($true)
{
    $Query = "select * from __instanceCreationEvent within 1 where targetInstance isa 'win32_Process' AND TargetInstance.Name = 'calc.exe'"
        $Eventwatcher = New-Object management.managementEventWatcher $Query

        $Event = $Eventwatcher.waitForNextEvent()

        $prog = Get-Process -Name calc
        $prog.PriorityClass = [System.Diagnostics.ProcessPriorityClass]::Idle
}