4

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?

briantist
  • 45,546
  • 6
  • 82
  • 127
miguello
  • 544
  • 5
  • 15

1 Answers1

6

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()
}
briantist
  • 45,546
  • 6
  • 82
  • 127
  • yeah, this works. Thanks! I tried through ```$pinfo = New-Object System.Diagnostics.ProcessStartInfo``` and ```$p.StartInfo = $pinfo $p.Start() | Out-Null $p.WaitForExit() ``` but it didn't work – miguello Aug 14 '21 at 00:23
  • @miguello You could also use `$MyProcess.WaitForExit()` with the output from `Start-Process`, rather than having to make an additional call. It also has a `.HasExited` property, but it's better not to do your own looping and polling unless you had to do some other action while you wait. – briantist Aug 14 '21 at 00:50