Powershell Start Process, Wait with Timeout, Kill and Get Exit Code
<p>I want to repeatedly execute a program in a loop.</p>

<p>Sometimes, the program crashes, so I want to kill it so the next iteration can correctly start. I determine this via timeout.</p>

<p>I have the timeout working but cannot get the Exit Code of the program, which I also need to determine its result.</p>

<p>Before, I did not wait with timeout, but just used -wait in Start-Process, but this made the script hang if the started program crashed. With this setup I could correctly get the exit code though.</p>

<p>I am executing from ISE.</p>

<pre><code>for ($i=0; $i -le $max_iterations; $i++)
{
    $proc = Start-Process -filePath $programtorun -ArgumentList $argumentlist -workingdirectory $programtorunpath -PassThru
    # wait up to x seconds for normal termination
    Wait-Process -Timeout 300 -Name $programname
    # if not exited, kill process
    if(!$proc.hasExited) {
        echo "kill the process"
        #$proc.Kill() &lt;- not working if proc is crashed
        Start-Process -filePath "taskkill.exe" -Wait -ArgumentList '/F', '/IM', $fullprogramname
    }
    # this is where I want to use exit code but it comes in empty
    if ($proc.ExitCode -ne 0) {
       # update internal error counters based on result
    }
}
</code></pre>

<p>How can I</p>

<ol>
<li>Start a process</li>
<li>Wait for it to orderly execute and finish</li>
<li>Kill it if it is crashed (e. g. hits timeout)</li>
<li>get exit code of process</li>
</ol>