Powershell启动过程,等待超时,杀死并获取退出代码
我想循环重复执行一个程序。Powershell启动过程,等待超时,杀死并获取退出代码
有时,程序崩溃,所以我想杀了它,所以下一次迭代可以正确开始。我通过超时确定这一点。
我有超时工作,但无法获得该程序的退出代码,我也需要确定其结果。
之前,我并没有等待超时,而是使用了 - 在Start-Process中等待,但是如果启动的程序崩溃,这会使脚本挂起。有了这个设置,我可以正确地得到退出代码。
我从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
}
}
我怎样才能
- 启动一个进程
- 等待它的有序进行和完成
- 杀死它,如果它的崩溃(如打超时)
- 获取退出代码的过程
您可以终止进程更多si mply使用$proc | kill
或$proc.Kill()
。要知道,你将无法取回在这种情况下,退出代码,您应该相当刚刚更新内部错误计数器:
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 -ea 0 -ev timeouted
if ($timeouted)
{
# terminate the process
$proc | kill
# update internal error counter
}
elseif ($proc.ExitCode -ne 0)
{
# update internal error counter
}
}
谢谢!等待进程在你的解决方案中等待正确的时间为400秒,但是“#终止进程”子句在超时之后永远不会打 - 也是这样,进程永远不会被终止,并且在下一次迭代之后,2个进程正在运行。 (我用一个小超时测试来强制这种情况。) –
你说得对,我认为Wait-Process会返回一些东西。我编辑了我的答案,现在我将错误消息分配给$超时,并且在发生超时的情况下,它被设置。 –
谢谢! (有一个小错字。)工作很好! –
【如何等待和杀死在PowerShell中的超时处理(HTTPS: //*.com/q/19532998/995714) –