Powershell Start Process, Wait with Timeout, Kill and Get Exit Code

后端 未结 1 1515
栀梦
栀梦 2020-12-06 01:46

I want to repeatedly execute a program in a loop.

Sometimes, the program crashes, so I want to kill it so the next iteration can correctly start. I determine this vi

相关标签:
1条回答
  • 2020-12-06 02:35

    You can terminate the process more simply using $proc | kill or $proc.Kill(). Be aware, that you won't be able to retrieve a exit code in this case, you should rather just update the internal error counter:

    for ($i=0; $i -le $max_iterations; $i++)
    {
        $proc = Start-Process -filePath $programtorun -ArgumentList $argumentlist -workingdirectory $programtorunpath -PassThru
    
        # keep track of timeout event
        $timeouted = $null # reset any previously set timeout
    
        # wait up to x seconds for normal termination
        $proc | Wait-Process -Timeout 4 -ErrorAction SilentlyContinue -ErrorVariable timeouted
    
        if ($timeouted)
        {
            # terminate the process
            $proc | kill
    
            # update internal error counter
        }
        elseif ($proc.ExitCode -ne 0)
        {
            # update internal error counter
        }
    }
    
    0 讨论(0)
提交回复
热议问题