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
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
}
}