Search code examples
powershellwaitstart-process

How to change priority of process in powershell, if it runs with -Wait parameter?


I am using a scheduled PowerShell script to start the same process with various arguments many times in a loop. Process is very heavy on computations and runs for a long time, and I have thousands of iterations. I noticed, that since it's a scheduled script, it runs with BelowNormal priority. And even if I bump it, any spawned processes are still BelowNormal. So, since I run this process in a loop thousands of times, I need to use -Wait like this:

foreach($list in $lists){

        Start-Process -FilePath $path_to_EXE -ArgumentList $list -NoNewWindow -Wait

}

Now, I want to bump the priority, and one way I found was to do this:

($MyProcess = Start-Process -FilePath $path_to_EXE -ArgumentList $list  -NoNewWindow -Wait -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal

However, it doesn't work, because it needs to wait until process finishes, then execute whatever is outside of parenthesis: (...).PriorityClass = ... I can't let it proceed with the loop and spawn thousands of processes, I need to run one at a time, but how do I tell it to bump the priority, and then wait?


Solution

  • You can do the act of waiting within your code, by way of Wait-Process:

    foreach($list in $lists) {
        $MyProcess = Start-Process -FilePath $path_to_EXE -ArgumentList $list  -NoNewWindow -PassThru
        $MyProcess.PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal
        $Myprocess | Wait-Process
    }
    

    The object returned from Start-Process also has a .WaitForExit() method:

    foreach($list in $lists) {
        $MyProcess = Start-Process -FilePath $path_to_EXE -ArgumentList $list  -NoNewWindow -PassThru
        $MyProcess.PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal
        $Myprocess.WaitForExit()
    }