我想在循环中重复执行一个程序。
有时候,这个程序会崩溃,因此我想杀掉它,以便下一次迭代可以正确启动。我通过超时来确定这一点。
我已经设置了超时,但无法获取程序的退出代码,这也是我需要确定其结果的原因。
以前,我没有使用超时等待,而是在Start-Process中使用了-wait,但如果启动的程序崩溃,脚本就会挂起。虽然在这种设置下,我可以正确地获取退出代码。
我是从ISE执行的。
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() <- 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
}
}
我该如何
- 启动进程
- 等待进程有序执行并完成
- 在进程崩溃(如超时)时杀死它
- 获取进程的退出代码